我试着去使用在PHP中的preg_replace函数的字符串完全匹配。我只想匹配有一个“@”符号实例。我还需要一个变量作为模式传递英寸
$x = "@hello, @@hello, @hello, @@hello"
$temp = '@hello'
$x = preg_replace("/".$temp."/", "replaced", $x);
结果应该仅仅是:
$x = "replaced, @@hello, replaced, @@hello"
先感谢您。
添加否定look-behind (?<!@)
如果$temp
前面带有@
将失败匹配(或在平淡的话,如果有@
前@hello
,不匹配的话):
$x = "@hello, @@hello, @hello, @@hello";
$temp = '@hello';
$x = preg_replace("/(?<!@)".$temp."/", "replaced", $x);
echo $x;
这里是a regex demo
另外,如果你到底有没有整字边界,追加\b
的模式刚刚结束,以确保您不更换@helloween
:
"/(?<!@)".$temp."\\b/"