应转义哪些字符以替换为 preg_replace

Which characters should be escaped in replacement with preg_replace

我注意到当替换有 \ 时,该功能将无法按预期工作。所以我应该转义反斜杠。

还有哪些字符应该转义?我没有成功找到任何文档。

我不能使用 preg_quote() 因为它用于转义模式而不是替换。

再次编辑:这是一个 single quote 的示例,它显示了反斜杠如何导致问题:

 $replacement = '<head>content [=11=]20 content</head>';
$subject = "<head>any header </head>";
$html_text = preg_replace ( "%<head>.*?</head>%s", $replacement, $subject, - 1, $count );
die ( $html_text );$subject, - 1, $count );
echo $html_text;

上面的例子应该打印:<head>content [=15=]20 content</head>。但它是打印 <head>content <head>any header </head>20 content</head>

如果您尝试匹配字符,应转义以下内容

\ ^ . $ | ( ) [ ]     * + ? { } ,

您要查找的文档在此处:Meta-characters。这些是您可以在正则表达式中使用的特殊字符,这意味着如果您需要逐字搜索它们,则需要对它们进行转义。

[=10=]2 是一个八进制数,当在 windows 终端上呈现时会显示一个小笑脸 ☻,然后是 [=11=]20 的尾随 0。在浏览器中查看时,您只会看到尾随的 0。有关转义序列,请参见 Double quoted 字符串。要使用双引号,您需要使用 \\0020.

您也可以使用Single quoted strings or Nowdoc

如果您从其他地方读取此字符串,您可以使用 addslashes().