I was wondering if it was possible to use regex or preg_match()
in array_seach()
or array_keys_exist
?
我想知道是否可以在array_seach()或array_keys_exist中使用正则表达式或preg_match()?
ie. array_keys_exist($array,"^\d+$")
to match all keys that are solely numeric characters
即。 array_keys_exist($ array,“^ \ d + $”)匹配所有仅为数字字符的键
2 个解决方案
#1
10
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
.
我不知道它是否完全符合您的需求,但您应该看一下preg_grep函数,它将检查正则表达式的字符串数组并返回所有匹配的数组元素。您可以通过在array_keys的返回值上使用preg_grep来对键执行相同的操作。
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.
这与array_search / array_key_exists的不同之处在于,它们在找到匹配后停止,因为可能只有一个匹配。另一方面,使用正则表达式可能有许多元素满足条件,因此preg_grep将返回所有这些元素。
#2
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.)
(也会有RecursiveRegexIterator,但这会增加语法开销。)
#1
10
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
.
我不知道它是否完全符合您的需求,但您应该看一下preg_grep函数,它将检查正则表达式的字符串数组并返回所有匹配的数组元素。您可以通过在array_keys的返回值上使用preg_grep来对键执行相同的操作。
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.
这与array_search / array_key_exists的不同之处在于,它们在找到匹配后停止,因为可能只有一个匹配。另一方面,使用正则表达式可能有许多元素满足条件,因此preg_grep将返回所有这些元素。
#2
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.)
(也会有RecursiveRegexIterator,但这会增加语法开销。)