Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

like image 789
Brook Julias Avatar asked Apr 27 '11 14:04

Brook Julias


2 Answers

I don't know whether it suits your needs exactly, but you should have a look at the preg_grep function, which will check an array of strings against a regex and return all matching array elements. You could do same with the keys, by using preg_grep on the return value of array_keys.

This is different from array_search / array_key_exists in the respect, that these stop after they have found a match, because there may only be one match. With regex on the other hand there may be many elements satisfying the condition, so preg_grep will return all of them.

like image 104
NikiC Avatar answered Oct 23 '22 23:10

NikiC


For that specific case you could use:

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

For matching keys with other regular expressions you would need a custom callback.

(There would also be RecursiveRegexIterator, but that's more syntax overhead.)

like image 44
mario Avatar answered Oct 24 '22 00:10

mario