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

拈花ヽ惹草 提交于 2021-02-08 20:53:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!