php 函数array_key_exists和正则表达式
是否可以将正则表达式与php函数一起使用?array_key_exists()
例如:
$exp = "my regex";
array_key_exists($exp, $array);
谢谢!
是否可以将正则表达式与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];