<?php
$string = '\n \n \n \n';
$patterns = '/\n/';
$replacements = '/\\n/';
echo preg_replace($patterns, $replacements, $string);
?>
这部分代码似乎无法正常工作,对此有何建议。它根本不回应任何事情。我可以让它与ereg一起工作,但想要转换为preg。ereg_replace和preg_replace
<?php
$string = '\n \n \n \n';
$patterns = '/\n/';
$replacements = '/\\n/';
echo preg_replace($patterns, $replacements, $string);
?>
这部分代码似乎无法正常工作,对此有何建议。它根本不回应任何事情。我可以让它与ereg一起工作,但想要转换为preg。ereg_replace和preg_replace
许多问题......
你们是不是要打造而成的新行字符的字符串?'\n \n \n \n'
是不是这样,它不工作。使用"\n \n \n \n"
和阅读有关字符串here的PHP官方手册。
您的模式未正确转义。尝试'/\\n/'
,无论如何我不确定你的版本不起作用。
您的'/\\n/'
更换的原因是什么? 请提供输入字符串和所需输出的示例。
如果你试图逃跑字符串将它们保存在数据库中,你完全在错误的道路。谷歌为php数据库转义,并阅读约mysql_escape_string()
(或同等的,如果你不使用MySQL)。有功能可以做到这一点,而你必须使用它们。你不能依赖(或者没有理由去做)使用正则表达式的自定义函数。
我试图逃避用户输入,所以如果他们输入\ n当它在数据库中更新它不仅\ n而是\\ n。 – mintuz 2012-02-20 17:20:16
@明图兹好吧,所以你**完全错误的方式**。我编辑我的答案,接受它,如果我对你的意图是正确的。 – 2012-02-20 17:22:48
如果你意味着\n
是一个新的行字符,您可能无法使用单引号('),用双引号(“)在这里,而不是
PHP文件:ereg has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.
不管怎么说,你的$模式不正确地转义。您需要四个\
的 - 请参阅下面:
<?php
$string = '\n \n \n \n';
$patterns = '/\\\\n/';
$replacements = '/\\n/';
echo preg_replace($patterns, $replacements, $string); // string(19) "/\n/ /\n/ /\n/ /\n/"
?>
ereg已被弃用。 – CBusBus 2012-02-20 17:23:59