5

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

Brook Julias
  • 2,085
  • 9
  • 29
  • 44

2 Answers2

11

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.

NikiC
  • 100,734
  • 37
  • 191
  • 225
1

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.)

mario
  • 144,265
  • 20
  • 237
  • 291
  • 1
    Better even `'ctype_digit'`. `is_numeric` typically is too much, unless you really want to match stuff like hex numbers and exponential notation. – NikiC Apr 27 '11 at 14:53