我想替换模式字符串' / r /'在一个主题字符串中' r'有预定的替代品,如" \\ 23"'和' [4]'。 所以(只显示我的替换数组的一个子集)我尝试:
$subject = 'r r';
$replacements = array('"\\23"', '[4]');
$replacements = array_map('preg_quote', $replacements);
print_r($replacements);
foreach($replacements as $replacement){
$subject = preg_replace('/r/', $replacement, $subject, 1);
}
echo $subject;
我想要的字符串是'" \\ 23" [4]&#39 ;, 但是我回来了" \ 23;" \ [4 \]',这两个字符都缺少并且有其他字符。
PHP有一个可以在这里工作的转义函数吗?我该怎么做?
注意:如果没有preg_quote行,结果就是'"" [4]'
答案 0 :(得分:0)
只需要preg_quote函数,所以删除它
将r
替换为您需要使用的"\\23"
:
$subject = 'r r';
$replacements = array('"\\\\23"', '[4]'); // here is double escaping, but only in code, for input you do no need to escape anyhitng
foreach ($replacements as $replacement)
$subject = preg_replace('/r/', addcslashes($replacement, '\\'), $subject, 1); // here is the addition of \ only to \, as it is required by preg_replace
echo $subject;
http://php.net/manual/en/function.preg-replace.php
要替换使用反斜杠,必须加倍(“\\\\”PHP字符串)。