PHP using preg_match or regex as value for array_search or key for array_keys_exist

I was wondering if it is possible to use regex or preg_match() in array_seach() or array_keys_exist ?

i.e. array_keys_exist($array,"^\d+$") to match all keys that are only numeric characters

+4
source share
2 answers

I don't know if this suits your needs, but you should look at the preg_grep function, which will check the array of strings against the regular expression and return all the relevant elements of the array. You can do the same with keys using preg_grep on the return value of array_keys .

This differs from array_search / array_key_exists in that they stop after they find a match, because there can only be one match. With a regular expression, on the other hand, there can be many elements satisfying the condition, so preg_grep will return them all.

+10
source

In this particular case, you can use:

 = array_filter(array_keys($array), "is_numeric") 

To match keys with other regular expressions, you need a special callback.

(There will also be a RecursiveRegexIterator , but this is more syntax overhead.)

+1
source

All Articles