2012-01-16 31 views
0

我知道这个问题以前已经被问过,但我只是搜索一下,找不到任何东西(可能是错误的词选择?)。 只是不要对我太生气,我惹毛了太...捕获一个字符串中的新行

我想

$string = ' 
This is a line 
This is another line 
'; 

要显示的HTML页面

This is a line 
This is another line 

当我做echo $string;。 如何捕获返回键或新行,并将其替换为<br>

回答

2

尝试nl2br()功能:

echo nl2br($string); 

将返回:

<br> 
This is a line<br> 
This is another line<br> 

要剪掉开头和结尾的新生产线,使用trim()

echo nl2br(trim($string)); 

将返回:

This is a line<br> 
This is another line 
+0

+1为先。 – 2012-01-16 18:26:47

+0

这工作得很好。 – Shoe 2012-01-16 18:28:30

2

您可以使用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 /> 
*/ 
1

使用nl2br功能是这样的:

echo nl2br($string); 
0

如果你不nl2br得到它,你的新行字符不能的\ n。

print nl2br(str_replace(array("\r\n", "\r"), "\n", $string); 
0

你为什么不使用:

$string = " 
This is a line\n 
This is another line 
"; 

? 或使用

$string = <<<EOF 
    This is a line 
    This is another line 
EOF; 
相关问题