如何在 preg_replace 中引用替换?

How to quote replacement in preg_replace?

例如在下面的代码中,如果用户希望模板的新内容是字符串 C:\Users\Admin</code> 部分将变成 <code>BEGIN this was the original content of the template END,这是我不想要的。

preg_replace('/(BEGIN.*?END)/su', $_POST['content'], $template);

简而言之,使用这个函数引用动态替换模式:

function preg_quote_replacement($repl_str) {
    return str_replace(array('\', '$'), array('\\', '\$'), $repl_str);
}

问题是,您需要转义替换模式中的反斜杠。见 preg_replace docs:

To use backslash in replacement, it must be doubled ("\\" PHP string).

仅需 str_replace 函数即可完成:

$repl = 'C:\Users\Admin';
$template = "BEGIN this was the original content of the template END";
echo preg_replace('/(BEGIN.*?END)/su', str_replace('\', '\\', $repl), $template);

IDEONE demo

但是,注意 $ 符号在替换模式中 是特殊的。因此,我们也需要转义这个符号。这些初步替换的顺序很重要:首先,我们需要转义 \,然后是 $:

$r = '';
echo preg_replace('~(B.*?S)~', str_replace(array('\', '$'), array('\\', '\$'), $r), "BOSS");

参见 IDEONE demo(在您的代码中,preg_replace('/(BEGIN.*?END)/su', str_replace(array('\', '$'), array('\\', '\$'), $_POST['content']), $template); 或使用我在 post 开头添加的函数)。

您可以使用 T-Regx which automatically quotes all kinds of references with replacing:

pattern('(\d+)cm')->replace('I have 15cm and 192cm')->all()->with('<\2>');

结果

I have <> and <>

也适用于 </code> 和 <code> 引用。

PS:T-Regx 也有用于在 模式 中引用用户数据的工具,使用 pattern building!