我目前正在使用此代码从数据库
打印多行文本$query_content= "select * from home ";
$result_content= mysql_query($query_content,$con);
while ($text = mysql_fetch_array($result_content))
{
$content = $text['homecontent'];
}
使用此HTML代码:
<p>
<?php print $content; ?>
<p/>
数据库中的文字是:
abc
def
ghi
但我得到了这个
abc def ghi
有什么想法吗?
感谢。
答案 0 :(得分:6)
您可以在php中使用内置函数nl2br。这会将\n\r
(新行)转换为html的<br>
。
<p>
<?php
print nl2br( $content );
?>
<p/>
如果您希望拥有xhtml或html5兼容网站,则应将第二个参数设置为true
以使<br>
xhtml兼容,<br />
<p>
<?php
print nl2br( $content, true );
?>
<p/>
答案 1 :(得分:3)
echo str_replace(array("\r\n", "\n", "\r"), "<br>", $content);
问题在于,在文本中你有一个换行符“\ n”,“\ r”或他的组合,它们在html中显示为空格(空格字符)。
要在html中插入真正的“换行符”,必须使用标记<br/>
。
所以我写了一个简单的例子,将所有换行符号替换为&lt; br&gt; HTML标签。
在php中存在特殊功能string nl2br ( string $string [, bool $is_xhtml = true ] )
,它几乎完全相同,但我认为,更快更正确。