PHP preg_replace 替换中的任何文本

标签 php regex preg-replace replace

如何在替换中用任何文本和符号替换文本?因为当我使用反斜杠时,它被严重替换了。

$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/

相关文章:

ruby - 在 ruby​​ 中拆分句子的更好的正则表达式?

php - preg_replace_callback 在参数 2 处调用 $this->method ('\\1' )

php - preg_replace 的正则表达式

php - XMLHttpRequest 将变量传递给 php 脚本

php - Mysql 服务器不再与服务器名连接

php - Bootstrap 多级下拉不起作用

php - 无法将从 sql 查询获取的元素添加到数组

javascript - 用里面的数据替换html中的输入文本字段

python - 如何从 Pandas 数据框中的字典中删除大括号、撇号和方括号 (Python)

php - 用于数据库和网络安全的 preg_replace 函数