似乎无法将精确字符串与 Preg_replace 匹配

Cant seem to match Exact string with Preg_replace

我正在尝试使用 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;

IDEONE demo

这里是a regex demo

此外,如果您在末尾有整个单词边界,请将 \b 附加到模式的末尾,以确保您不会替换 @helloween:

"/(?<!@)".$temp."\b/"