使用php在数组中查找关键字?

时间:2013-10-23 08:53:08

标签: php arrays sorting search multidimensional-array

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

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但是没有得到正确答案

请告知

2 个答案:

答案 0 :(得分: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);

希望这对您有用。

答案 1 :(得分:2)

一个简单的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
)