Regexp来匹配一个被单词边界包围的单词,其中不包括正斜杠


Regexp to match a word, surrounded by word boundaries, which don't include forward slash

是否有可能使PHP regex字边界不匹配某些字符作为字边界?

例如,当我在下面运行/'btwo words'b/ RegExp时,我不想要任何匹配:

google.com/two words
stackoverflow.com/login?two words
yahoo.com/topics/99421231#$two words

然而,我希望匹配以下内容:

two words
one two words three
# two words
(two words)
.two words
!two words
PHP代码:preg_match("/'btwo words'b/", $text, $result);

您可以使用Negative Lookbehind,列出您想要在字符类中排除的内容。

preg_match('~(?<![/?$])'btwo words'b~i', $text, $result); 

现场演示