【问题标题】:PHP preg_replace any text in replacementPHP preg_replace 替换中的任何文本
【发布时间】:2012-03-08 02:34:55
【问题描述】:

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

$text = 'hello replacement world';

$text = preg_replace('#replacement#ui', '28\01\12', $text);

结果

hello 28 world

在使用模式之前进行替换的解决方案

$pattern = '28\01\12';
$pattern = str_replace('\\', '\\\\\\\\', $pattern);

这只是一个例子,实际工作中需要使用更复杂的模式,替换将包括任何文本

【问题讨论】:

  • 为什么要使用 preg_replace?对于这种情况,简单的 str_replace 会快得多。
  • 模式比较复杂,举个例子。

标签: php regex preg-replace replace


【解决方案1】:
$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

【讨论】:

  • 好的,使用 $text = preg_replace('#replacement#ui', '28\\\\01\\\\12', $text);我需要使用 preg_replace 导致模式更复杂。请告诉我,为了避免问题,我还需要转义哪些符号?
【解决方案2】:
$text = 'hello replacement world';

$text = preg_replace('#replacement#ui', '28\\01\\12', $text);

发生这种情况是因为您必须转义字符串中的反斜杠。

【讨论】:

  • 好的,使用 $text = preg_replace('#replacement#ui', '28\\\\01\\\\12', $text);我需要使用 preg_replace 导致模式更复杂。请告诉我,为了避免问题,我还需要转义哪些符号?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-15
  • 1970-01-01
  • 2015-05-19
  • 1970-01-01
  • 1970-01-01
  • 2016-08-14
  • 1970-01-01
相关资源
最近更新 更多