2014-10-10 113 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