<?php
$string = '\n \n \n \n';
$patterns = '/\n/';
$replacements = '/\\n/';
echo preg_replace($patterns, $replacements, $string);
?>这段代码似乎不起作用,任何关于为什么会发生这种情况的建议。它根本不会回响任何东西。我可以让它与ereg一起工作,但我想换成preg。
发布于 2012-02-21 01:05:01
这里有很多问题。
'\n \n \n \n'不是这样的,它不起作用。使用"\n \n \n \n"并阅读PHP官方手册关于字符串的.'/\\n/',不管怎么说,我不确定你的版本不能工作。'/\\n/'的原因是什么?请提供一个输入字符串和所需output.的示例
如果您试图转义字符串以将其保存在数据库中,那么您完全是在错误的上进行。在谷歌上搜索php数据库转义,并阅读有关的信息(如果你不使用MySQL,也可以阅读类似的内容)。有一些函数可以做到这一点,你必须使用它们()。您不能依赖(或者没有理由这样做)使用正则表达式的自定义函数。
发布于 2012-02-21 01:09:58
PHP文档:ereg has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.
不管怎样,你的$patterns没有被正确地转义。你需要四个\-见下图:
<?php
$string = '\n \n \n \n';
$patterns = '/\\\\n/';
$replacements = '/\\n/';
echo preg_replace($patterns, $replacements, $string); // string(19) "/\n/ /\n/ /\n/ /\n/"
?>发布于 2012-02-21 01:04:04
如果您希望\n是换行符,则不能使用单引号('),而应使用双引号(“
https://stackoverflow.com/questions/9365149
复制相似问题