为什么这个正则表达式找一个简单的字符串不起作用


why does this regex to find a simple string not work?

我试图找到一些样本字符串的匹配,但我对它为什么不起作用感到惊讶。

以下是一些应该找到的示例字符串(在"the"answers"turtle"或"fox"之间可以有任意数量的单词):

The Quick Brown Fox
The Slow Green Turtle
The Blah Blah Fox
The Blah Blah Blah Turtle

以下是不起作用的正则表达式:

if(preg_match("/the 'w* (fox|turtle)/i",$str)){
   echo "Match!<br>";
}

实际上是因为空间不是由''w处理的,您希望''w*与"Quick Brown"匹配。所以你可以试试

if(preg_match("/the['w ]*(fox|turtle)/i",$str))

以匹配两个块之间的任意数量的单词。

这是因为狐狸或乌龟前面有两个单词,而不是一个。

对于数量不确定的单词:

if ( preg_match('~'bthe(?> 'w+)*? (fox|turtle)'b~i', $str) )

注意:如果您想将"慢乌龟"与以下字符串匹配,则需要惰性量词*?The slow turtle and the quick fox(而不是所有句子)