PHP:为来自数据库的文本添加标签

时间:2016-01-24 11:36:15

标签: php mysql

我在MySql数据库中有一个文本。我想我不应该在数据库中放置标签。如果是这样,当我在html页面中回显该文本时,如何添加p标签?

例如我在数据库中有这个(三段):

第1段

第2段

第3段

当我在页面中使用php来回显文本时:

$text = $row['first'];
echo $text;//this gives: paragraph 1paragraph 2paragraph 3

这是我试图得到的:

<p>paragraph 1</p> 

<p>paragraph 2</p>

<p>paragraph 3</p>

2 个答案:

答案 0 :(得分:0)

你可以这样做:

echo '<p>'.$text.'</p>';

答案 1 :(得分:0)

如果你知道你有\n换行符,那么:

    // the full text
$text = "paragraph 1\n\nparagraph 2\n\nparagraph 3";

    // remove \n and space at start/end
$text = trim( $text ); 

    // the paragraph break 
$paragraphBreak = array("\r\n\r\n", "\n\r\n\r", "\n\n", "\r\r");

    // add the <p> tag
$text = '<p>'.str_replace( $paragraphBreak, '</p><p>', $text ).'</p>';

    // display with <br> tag
echo nl2br( $text );

这将添加<br>标记,如果你跳一行,则制作一个新的<p>