【问题标题】:Find Keyword in array using php?使用php在数组中查找关键字?
【发布时间】:2013-11-01 11:04:07
【问题描述】:

我有一个类似这种格式的关键字

sample text

我也有一个这样的数组,格式如下

Array
(
   [0] => Canon sample printing text
   [1] => Captain text
   [2] => Canon EOS Kiss X4 (550D / Rebel T2i) + Double Zoom Lens Kit
   [3] => Fresh sample Roasted Seaweed
   [4] => Fresh sample text Seaweed
)

我想在这个数组中找到sample text 关键字。 我的预期结果

Array
    (
       [0] => Canon sample printing text        //Sample and Text is here
       [1] => Captain text             //Text is here
       [3] => Fresh sample Roasted Seaweed       //Sample is here
       [4] => Fresh sample text Seaweed          //Sample text is here
    )

我已经在尝试strpos,但没有得到正确答案

请指教

【问题讨论】:

    标签: php arrays sorting search multidimensional-array


    【解决方案1】:

    一个简单的preg_grep 就可以完成这项工作:

    $arr = array(
        'Canon sample printing text',
        'Captain text',
        'Canon EOS Kiss X4 (550D / Rebel T2i) + Double Zoom Lens Kit',
        'Fresh sample Roasted Seaweed',
        'Fresh sample text Seaweed'
    );
    $matched = preg_grep('~(sample|text)~i', $arr);
    print_r($matched);
    

    输出:

    Array
    (
        [0] => Canon sample printing text
        [1] => Captain text
        [3] => Fresh sample Roasted Seaweed
        [4] => Fresh sample text Seaweed
    )
    

    【讨论】:

    • preg_grep()中的~i是什么意思?
    • i 用于忽略大小写,~ 在这里是正则表达式分隔符。
    【解决方案2】:

    preg_grep 成功了:

    $input = preg_quote('bl', '~'); // don't forget to quote input string!
    $data = array('orange', 'blue', 'green', 'red', 'pink', 'brown', 'black');
    
    $result = preg_grep('~' . $input . '~', $data);
    

    希望这对你有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-10
      • 1970-01-01
      • 2020-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-11
      • 1970-01-01
      相关资源
      最近更新 更多