【问题标题】:Using array_key_exists with preg_match将 array_key_exists 与 preg_match 一起使用
【发布时间】:2011-03-11 13:40:08
【问题描述】:

我正在尝试根据模式确定数组中是否存在一个或多个匹配项,

数组示例:

Array
(
    [author_id] => 1
    [channel_id] => 1
    [site_id] => 1
    [entry_id] => 6
    [url_title] => test_title_with_file2
    [title] => Test Title with file
    [field_id_1_directory] => 1
    [field_id_4_directory] => 1
    [submit] => Submit
    [entry_date] => 1278219110
)

我想确定 field_id_x_directory 键或键是否存在,如果存在,则循环遍历每个键并运行将“x”用作变量的函数。

非常感谢,

伊恩。

【问题讨论】:

    标签: php regex arrays


    【解决方案1】:
    foreach (array_keys($arr) as $k) {
        if (preg_match('/^field_id_(\\d+)_directory$/', $k, $matches)) {
            //do sth with $arr[$k] and $matches[1]
        }
    }
    

    【讨论】:

    • 非常感谢 :) 如果允许,我会在几分钟内接受答案!
    • 有一个 PHP 函数专门用于匹配数组中的项目... preg_grep 会是更好的选择
    【解决方案2】:

    更好的选择是:

    function preg_grep_keys( $pattern, $input, $flags = 0 )
    {
    $keys = preg_grep( $pattern, array_keys( \$input ), \$flags );
    $vals = array();
    foreach ( $keys as $key )
    {
        $vals[$key] = $input[$key];
    }
    return $vals;
    }
    

    【讨论】:

      【解决方案3】:
        $input = array (
        'hello'=>2,
        'hello stackoverflow'=>1,
        'hello world',
        'foo bar bas'=>4
      );
      $matches  = preg_grep ('/^hello$/i', array_keys($input));
       echo $input[$matches[0]];
      

      将返回 2

      【讨论】:

      • 您的解决方案似乎比公认的答案更优雅。但是它有一个小错误。 preg_grep 保留 array_keys 返回的数组中的索引。因此,如果您搜索“hello world”,您将找不到 $matches[0]。相反,您将拥有 $matches[2]
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-19
      • 2020-08-29
      相关资源
      最近更新 更多