【问题标题】:How to search a substring in PHP array using regExp如何使用 regExp 在 PHP 数组中搜索子字符串
【发布时间】:2011-12-12 10:04:00
【问题描述】:
   $array = array(
            array('foo_test1','demo_test1'),
            array('foo_test2','demo_test2'),
            array('blah_test1','exp_test1'),
            array('blah_test2','exp_test2'),
            array('foo_test3','demo_test3')
            )

如何使用 php 和 regExp 获取包含 foo 子字符串及其值的所有子数组。

预期输出:

$array = array(
        array('foo_test1','demo_test1'),
        array('foo_test2','demo_test2'),
        array('foo_test3','demo_test3')
        )

【问题讨论】:

    标签: regex arrays search substring


    【解决方案1】:

    你应该可以做到的

    preg_grep($pattern,$array)
    

    【讨论】:

    • 这正是您需要的代码。我也搜索了这个函数,但认为它会被称为“array_match”或类似的 stg。 :)
    【解决方案2】:
    $input  = array( /* your array */ );
    $output = array();
    
    foreach ( $input as $data ) {
      $len = length($data);
      for ( $i = 0; $i < $len; ++$i ) {
        if ( strpos($data[$i], 'foo') > -1 ) {
          $output[] = $data;
          break;
        }
      }
    }
    

    【讨论】:

      【解决方案3】:
      $array = array(
          array('foo_test1','demo_test1'),
          array('foo_test2','demo_test2'),
          array('blah_test1','exp_test1'),
          array('blah_test2','exp_test2'),
          array('foo_test3','demo_test3')
      );
      
      $search = 'foo';
      $res = array();
      foreach ($array as $arr) {
          foreach ($arr as $value) {
              if (preg_match('~'.preg_quote($search,'~').'~',$value)) {
              // if one of the values in that array
              // has the search word in it...
                  $res[] = $arr; break;
                  // push it into the $res and break
                  // the inner foreach loop
              }
          }
      }
      print_r($res);
      

      【讨论】:

        猜你喜欢
        • 2018-11-28
        • 2022-01-23
        • 1970-01-01
        • 1970-01-01
        • 2012-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-04
        相关资源
        最近更新 更多