2013-10-23 38 views
1

我有一個關鍵字這樣的格式使用php查找數組中的關鍵字?

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

一個簡單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); 

OUTPUT:

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

什麼呢?我是指preg_grep()? –

+0

'我'是爲了忽略大小寫,'〜'是正則表達式分隔符。 – anubhava

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); 

希望這將確保爲工作您。