PHP正则表达式必须包含几个单词,不能包含其他单词


php regex must contain several words and must not contain others

我需要创建一个php regex模式,如果字符串中有一个或多个特定单词,但其他一些单词不在,则返回true。

例如,假设我们想要允许单词'and', 'this', 'then';但是不要使用"不要"、"担心"answers"从不"这些词。

所以下面的句子应该是匹配的:"我喜欢这些东西"这个,那个"然后"我和你"

,但以下不应该:"我从来不喜欢这些东西"别担心。"不要担心这个和那个"我从不担心那些事。"我从不做某事"

真正的难点不仅在于'and' '或'and not'操作符的组合,还在于单词/字符串可以出现在句子中的任何地方。

谢谢你的帮助

function isAllowedSentence($str)
{
    return (preg_match('/'b(and|this|then)'b/i', $str) && !preg_match('/'b(don''t|worry|never)'b/i', $str));
}

echo isAllowedSentence('I like this stuff'); // true
echo isAllowedSentence('I never like this stuff'); // false
echo isAllowedSentence('I like Johnny Mathis'); // false

"And"answers"not"更难用regex实现。使用多个

会更容易
preg_match('/'b(?:and|this|then)'b/i', $str)
   &&
!preg_match('/'b(?:dont|worry|never)'b/i', $str)

但这是可以做到的。

首先,否定:

preg_match('/'b(?:and|this|then)'b/i', $str)
   &&
!preg_match('/^(?: (?!'b(?:dont|worry|never)'b). )*'z/isx', $str)

然后组合它们:

preg_match(
   '/
      ^
      (?= .* 'b(?:and|this|then)'b )
      (?= (?: (?!'b(?:dont|worry|never)'b). )*'z )
   /isx',
   $str
)

这在Perl中有效。未在PHP中测试。

Update: php化代码。删除了多余的斜杠。