我想用 \\n
替换 \n
,用 \\a
替换 \a
和等等……
所以这是我的正则表达式:
图案:
([\\])
应替换为:
$1$1
因此,如果输入字符串是\n
,它将被替换为\n
。
(我已经在 http://www.regexe.com/ 测试过它并且有效)
然后我有了这段 PHP 代码:
preg_replace('/([\\])/', '$1$1', "\n a");
并认为它会输出\n a,但我得到了这个错误:
Warning: preg_replace(): Compilation failed: missing terminating ] for character class at offset 5
所以我已经逃脱了[
。
现在我的代码是
preg_replace('/(\[\\])/','$1$1',"\n a");
但是......这并没有像我想要的那样工作,因为现在它没有用 \\n
替换 \n
。
我做错了什么?
最佳答案
您不需要使用 preg_replace
,您可以使用 str_replace
,因为您没有匹配模式。并且你需要将主题字符串放在单引号中,否则 \n
将被视为换行符的转义序列。
str_replace('\\', '\\\\', '\n a');
参见 What is the difference between single-quoted and double-quoted strings in PHP?
关于PHP、正则表达式 - 如何使用 preg_replace 转义\n?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35515871/