带小括号的精确单词的正则表达式在 PHP 中不起作用

Regex for exact word with small bracket not working in PHP

$string = 'Wow ABC (R+R) : Weldone boy (My Love)';
$variable = "ABC (R+R)"; // this will be dynamic, could be BC (R+R) so I must use \b as boundary in pattern
$pattern = "/\b$variable\b/i";

echo preg_match($pattern, $string)? 'matched' : 'not matched';

这不匹配。即使我已经尝试过模式 "/\bABC \(R\+R\)\b/i" 但它仍然不匹配。

Here 是我测试的 link。

模式应转义加号,最后一个单词边界应为空白边界

\bABC \(R\+R\)(?!\S)

看到一个php demo

代表“第四只鸟”的回答,下面是完整的例子:

$string = 'wow Brands - Love Joy. (R+R) : Weldone boy (My Love)';
$variable = "Brands - Love Joy. (R+R)";

$pattern = "/\b".preg_quote($variable, "/")."(?!\S)/";
$pattern = "/\b\Q$variable\E(\s|$)/";  // this also works (my solution)

echo preg_match($pattern, $string)? 'matched' : 'not matched';

\Q 和 \E 也用于不特殊处理其中的字符。这不会转义正斜杠 (/)。

preg_quote 使您的字符串正则表达式准备就绪(转义特殊字符),在这里我们也可以使用第二个参数 [=23= 转义正斜杠 (/) ].