Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

php - finding keys in an array that match a pattern

I have an array that looks like:

 Array ( [2.5] => ABDE [4.8] => Some other value ) 

How would I find any key/value pair where the key matches a pattern? I will know the value of the first digit in the key,but not the second. so for example, using a prefix of "2.", I want to somehow be able to find the key "2.5" and return both the key and the value "ABDE".

I was thinking about using a regular expression with a pattern like:

$prefix = 2;
$pattern = '/'.$prefix.'.d/i';

and then looping through the array and checking each key. (by the way, just for demo purposes, $prefix has been hardcoded to 2, but in the real system, this is a value provided by the user's input).

I'm wondering if there's a simpler way to do this?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you need something like this:

$keys = array_keys($array);
$result = preg_grep($pattern, $keys);

The result will be a array that holds all the keys that match the regex. The keys can be used to retrieve the corresponding value.

Have a look at the preg_grep function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...