2013-09-20 37 views
0

我有匹配單詞的數組:正則表達式檢查,如果數組包含一些話

$search = array("lorem","dolor","sit"); 

和陣列中搜索:

$results= array(
     "Lorem ipsum dolor sit amet, consectetur", 
     "Ut enim ad minim veniam, quis nostrud exercitation" 
     "Duis aute irure dolor in reprehenderit in voluptate velit esse" 
     "Excepteur sint occaecat cupidatat non proident" 
    ); 

是否有一個正則表達式返回真正其中兩個給定的單詞是否匹配?

+0

爲什麼它必須是正則表達式? – meda

+0

,因爲我需要在xpath中使用它比較 –

+0

xpath compare()做字符串比較,不是嗎? – Anthony

回答

0

您可以生成一個正則表達式這個

$regex = '/(' . implode('|', $search) . ')/i'; 

搜索,這將是:

/(lorem|dolor|sit)/i 

/i使其無殼。

然後,您可以使用返回值preg_match_all()來查看匹配單詞的數量。

1

您可以在正則表達式中使用單詞邊界\b

單詞邊界是\ w和\ W(非單詞char)之間的位置,或者在字符串開始或結束(分別)與單詞字符結尾的位置。

因此,也許這樣的事情..

foreach ($results as $result) { 
    $pattern = "/\b(" . implode('|', $search) . ")\b/i"; 
    $found = preg_match_all($pattern, $result, $matches); 

    if ($found) { 
    print_r($matches[0]); 
    } 
} 

或者你可以與你的搜索陣列做掉,只是把它作爲一個正則表達式:

foreach ($results as $result) { 
    $found = preg_match_all("/\b(?:lorem|dolor|sit)\b/i", $result, $matches); 
    if ($found) { 
    print_r($matches[0]); 
    } 
} 

輸出:

Array 
(
    [0] => Lorem 
    [1] => dolor 
    [2] => sit 
) 
Array 
(
    [0] => dolor 
) 
相關問題