我知道这个问题以前已经被问过,但我只是搜索一下,找不到任何东西(可能是错误的词选择?)。 只是不要对我太生气,我惹毛了太...捕获一个字符串中的新行
我想
$string = '
This is a line
This is another line
';
要显示的HTML页面
This is a line
This is another line
当我做echo $string;
。 如何捕获返回键或新行,并将其替换为<br>
?
我知道这个问题以前已经被问过,但我只是搜索一下,找不到任何东西(可能是错误的词选择?)。 只是不要对我太生气,我惹毛了太...捕获一个字符串中的新行
我想
$string = '
This is a line
This is another line
';
要显示的HTML页面
This is a line
This is another line
当我做echo $string;
。 如何捕获返回键或新行,并将其替换为<br>
?
您可以使用PHP函数nl2br。它不会替换换行符,而是在它们旁边插入<br />
(这对您的目的而言是完全正确的)。使用
你的例子:
$string = '
This is a line
This is another line
';
echo nl2br($string);
/* output
<br />
This is a line<br />
This is another line<br />
*/
使用nl2br
功能是这样的:
echo nl2br($string);
如果你不nl2br得到它,你的新行字符不能的\ n。
print nl2br(str_replace(array("\r\n", "\r"), "\n", $string);
你为什么不使用:
$string = "
This is a line\n
This is another line
";
? 或使用
$string = <<<EOF
This is a line
This is another line
EOF;
+1为先。 – 2012-01-16 18:26:47
这工作得很好。 – Shoe 2012-01-16 18:28:30