2014-10-10 111 views
4

確定可以說我whant在一個句子匹配3個字......但我NEET以任何順序相匹配它們,例如:匹配多個單詞用正則表達式

$sentences = Array(
    "one two three four five six seven eight nine ten", 
    "ten nine eight seven six five four three two one", 
    "one three five seven nine ten", 
    "two four six eight ten", 
    "two ten four six one", 
); 

所以我需要匹配單詞「two」,「four」&「ten」,但以任意順序,他們之間可以或不可以有任何其他單詞。我嘗試

foreach($sentences AS $sentence) { 
    $n++; 
    if(preg_match("/(two)(.*)(four)(.*)(ten)/",$sentence)) { 
     echo $n." matched\n"; 
    } 
} 

但這隻會匹配句1,我需要在句子1,2,4 & 5.

我希望你能幫助匹配... 商祺! (並對不起,我的英語)

+1

[試試這個...](http://stackoverflow.com/questions/3533408/regex-i-want-this-and-that-and-that-in-any )它不是爲PHP,但它是正則表達式... [和實際文檔](http://www.regular-expressions.info/lookaround.html) – 2014-10-10 23:37:53

+3

也...你[可能不需要正則表達式]( http://xkcd.com/1171/)...只需檢查字符串是否包含其他字符串。 http://stackoverflow.com/questions/4366730/how-to-check-if-a-string-contains-specific-words – 2014-10-10 23:40:21

回答

4

您可以使用積極Lookahead來實現這一點。

先行的方式很適合匹配包含這些子串的字符串,而不管順序如何。

if (preg_match('/(?=.*two)(?=.*four)(?=.*ten)/', $sentence)) { 
    echo $n." matched\n"; 
} 

Code Demo

+0

謝謝!那樣做了! :d – 2014-10-11 19:58:55