如何在preg_replace中引用替换


How to quote replacement in preg_replace?

例如,在下面的代码中,如果用户希望模板的新内容是字符串C:'Users'Admin'1,那么'1部分将变成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文档:

若要在替换中使用反斜杠,必须将其加倍("''''" PHP字符串)。

只需一个str_replace函数即可完成:

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

查看IDEONE演示

但是,注意$符号在替换模式中也是特殊符号。因此,我们也需要逃离这个符号。这些预备替换的顺序很重要:首先,我们需要逃离',然后是$:

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

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

您可以使用T-Regx,它通过替换自动引用所有类型的引用:

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

中的结果

I have <'2> and <'2>

也适用于$1${2}参考文献。

附言:T-Regx也有工具引用模式中的用户数据,使用模式构建!

我在寻找相同的函数,但我了解到,不应该引用替换函数。您应该使用preg_replace_callback。https://github.com/php/php-src/issues/9663