问题
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
回答1:
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.
回答2:
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.)
来源:https://stackoverflow.com/questions/5805980/php-using-preg-match-or-regex-as-value-for-array-search-or-the-key-for-array-key