php preg_replace 带括号的字符串

php preg_replace strings with brackets

我正在尝试替换一些文本,如果它前面没有点 (.),但我的函数似乎结果包含一个意外的斜杠...

<?php

$test="function insertXYZ(e){e.insertXYZ()};";
$search="insertXYZ(";
$replace="zzzz(";

$search=str_replace("(", '\(', $search);
//echo $search."\n\n";
$pattern = '\b' . $search;
$replaceException="999";

$test=preg_replace('/' . "\.".$pattern . '/', "$replaceException", $test);
$test=preg_replace('/' . $pattern . '/', $replace, $test);
$test=preg_replace('/' . $replaceException . '/', ".$search", $test);

echo $test;
?>

可以在 http://sandbox.onlinephpfunctions.com/code/24cab4eece20d22a11dd887da44d63e393b51aa9

找到此代码的示例

输出...

function zzzz(e){e.insertXYZ\()};
                            ^

但我希望输出显示为...

function zzzz(e){e.insertXYZ()};
                            ^

我哪里错了?

这是因为在这一行中,您要添加反斜杠,然后再不删除它

$search=str_replace("(", '\(', $search);

您可以将代码更改为以下内容,这样您就无需手动转义该括号。

// $search=str_replace("(", '\(', $search); <-- Removed
$pattern = '\b' . preg_quote($search);

但是,您可以使用更少的代码获得相同的输出

$testString = "function insertXYZ(e){e.insertXYZ()};";
$regex = "/[^.](insertXYZ)/s";
echo(preg_replace($regex, " zzzz", $testString));
[^.] - Character group looking where there's NOT a dot character
(insertXYZ) - matches 'insertXYZ' exactly (case sensitive)
/s - Single line modifier so there's no need to escape the dot character