能否在php函数array_key_exists()
中使用正则表达式?
比如:
$exp = "my regex";
array_key_exists($exp, $array);
谢谢!
你可以使用 array_keys() 来提取数组键,并在该数组上使用 preg_grep():
function preg_array_key_exists($pattern, $array) {
$keys = array_keys($array);
return (int) preg_grep($pattern,$keys);
}
.
$arr = array("abc"=>12,"dec"=>34,"fgh"=>56);
var_dump(preg_array_key_exists('/c$/',$arr)); // check if a key ends in 'c'.
var_dump(preg_array_key_exists('/x$/',$arr)); // check if a key ends in 'x'.
function preg_array_key_exists($pattern, $array) {
// extract the keys.
$keys = array_keys($array);
// convert the preg_grep() returned array to int..and return.
// the ret value of preg_grep() will be an array of values
// that match the pattern.
return (int) preg_grep($pattern,$keys);
}
输出:
$php a.php
int(1)
int(0)
$keys = array_keys($array);
foreach ($keys as $key)
if (preg_match($exp, $key) == 1)
return $array[$key];
preg_match()
只匹配模式的第一个出现。因此它只能返回 0
或 1
。请参见 http://php.net/preg_match - Andrew Moore