【问题标题】:php function array_key_exists and regular expressionsphp 函数 array_key_exists 和正则表达式
【发布时间】:2010-03-18 15:36:35
【问题描述】:

php函数array_key_exists()可以使用正则表达式吗?

例如:

$exp = "my regex";  
array_key_exists($exp, $array);

谢谢!

【问题讨论】:

    标签: php regex


    【解决方案1】:

    您可以使用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)
    

    【讨论】:

    • 你可以使用array_keys()代替翻转
    【解决方案2】:

    不,恐怕不会。您可以迭代数组键并对它们执行匹配:

    $keys = array_keys($array);
    foreach ($keys as $key)
      if (preg_match($exp, $key) == 1)
        return $array[$key];
    

    【讨论】:

    • 或者只是 if(preg_match(...)) 在多个结果出现的情况下。
    • @zerkms: preg_match() 只匹配第一次出现的模式。因此它只能返回01。请看php.net/preg_match
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 2012-07-23
    • 1970-01-01
    • 2013-04-05
    • 2014-05-28
    相关资源
    最近更新 更多