PHP函数array_key_exists和正则表达式 [英] php function array_key_exists and regular expressions
本文介绍了PHP函数array_key_exists和正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以将正则表达式与php函数array_key_exists()
一起使用?
Is it possible to use a regular expression with the php function array_key_exists()
?
例如:
$exp = "my regex";
array_key_exists($exp, $array);
谢谢!
推荐答案
您可以使用 array_keys(),然后使用 preg_grep()在该数组上:
You can extract the array keys using array_keys() and then use preg_grep() on that array:
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)
这篇关于PHP函数array_key_exists和正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文