如何在替换中用任何文本和符号替换文本?因为当我使用反斜杠时,它被严重替换了。
$text = 'hello replacement world';
$text = preg_replace('#replacement#ui', '28\01\12', $text);
结果
hello 28 world
使用模式之前进行替换的解决方案
$pattern = '28\01\12';
$pattern = str_replace('\\', '\\\\\\\\', $pattern);
这只是示例,在实际工作中需要使用更复杂的模式并且替换将包含任何文本
最佳答案
$text = preg_replace('#replacement#ui', '28\\01\\12', $text);
请参阅此处有关反斜杠的注释:http://php.net/manual/en/language.types.string.php
如果您只是搜索要替换的简单字符串,则应考虑使用 str_replace()
。就CPU而言,它更便宜。参见这里:http://php.net/manual/en/function.str-replace.php
更新:有关转义序列的更多信息:http://www.php.net/manual/en/regexp.reference.escape.php
关于PHP preg_replace 替换中的任何文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9315625/