使用正则表达式匹配任意顺序的多个单词

6

好的,假设我想在一个句子中匹配3个单词...但我需要以任意顺序匹配它们,例如:

$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
尝试这个...它不是针对PHP的,而是针对正则表达式的...还有实际的文档。请访问http://www.regular-expressions.info/lookaround.html。 - gloomy.penguin
3
在此情况下,你可能不需要使用正则表达式(Regex),只需检查字符串是否包含其他字符串。参考链接为https://dev59.com/3m855IYBdhLWcg3wZzXf。 - gloomy.penguin
1个回答

7
你可以使用正向先行断言来实现这一点。
正向先行断言的方法适用于匹配包含这些子字符串的任意顺序的字符串。
if (preg_match('/(?=.*two)(?=.*four)(?=.*ten)/', $sentence)) {
    echo $n." matched\n";
}

Code Demo


谢谢!完成了! :D - Juan Carlos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接