如何回显MySQL数据库中的换行符?

时间:2016-02-14 09:53:25

标签: php mysql echo

我创建了一个简单的墙贴功能,就像在FaceBook上一样。

用户撰写帖子,将帖子提交给数据库,然后回传到网站上;一切正常。

唯一的问题是,当文本回显到网站上时,换行符不是。所以,我打字:

  

“嘿,这是一个帖子。

     

这是一个新段落“

,显示为:

  

“嘿,这是一个帖子。这是一个新的段落”

我在这里看到一些帖子说使用nl2br()函数和输入/ n换行,但是我真的不希望我的用户每次想要一个新的时候都要写'/ n'他们只需按下键盘上的回车键即可。

换行符存储在数据库中,所以我不知道为什么它没有被回显。有人可以帮忙吗?

不确定代码是否必要,但我会发布以防万一。

while($wallposts = mysql_fetch_assoc($getwallposts)) {
    $postid = $wallposts['id'];
    $postedby_username = $wallposts['postedby'];
    $wallpostdate = $wallposts['dateposted'];
    $wallpost = $wallposts['post'];

    $querypostedby_info = mysql_query("SELECT * FROM `users` WHERE `username`='$postedby_username'");

    //get the info above
    if (mysql_num_rows($querypostedby_info)===1) {
        $getpostedby_info = mysql_fetch_assoc($querypostedby_info);

        $postedby_id = $getpostedby_info['id'];
        $postedby_profilepicture = $getpostedby_info['profilepicture'];
    }

    //display the posts
    $wallpoststicker = 
    "
    <div id='wallpost-container'>
        <div id='wallpost-header'>
            <img src='$postedby_profilepicture'><div id='wallpost-header-by'><a href='/profile.php?id=$postedby_id'>$postedby_username</a> said:</div>
            <div id='wallpost-date'>&bull; $wallpostdate</div> 
        </div>
        <div id='wallpost-content'>
            $wallpost
        </div>
    </div>
    ";
}

2 个答案:

答案 0 :(得分:3)

PHP function nl2br converts newlines to "<br>" breaks.
So, $wallpost=nl2br($wallpost); should accomplish the task.

答案 1 :(得分:1)

建议nl2br的答案很棒,我会采用这种方法。

在您的原始问题中,我认为存在一些混淆 - 用户每次想要换行时都不会输入\n。斜线用于转义(特殊字符,而不是正常的n)。

在Windows计算机上,Enter键等同于\r\n,其中\r为回车符,\n为新行。在Linux或类似设备上,Enter键为\n\r的ascii值为13,\n&#39; s为10。

因此,EOL(行尾)将为\r\n\n。 Php具有nl2br函数,其目的是将所有\r\n\n替换为<br>,换行符的html标记。