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


How do I echo line breaks from a MySQL database?

我创建了一个简单的墙帖子功能,就像在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>
    ";
}

PHP 函数 NL2BR将换行符转换为"<br>"分隔符。
所以,$wallpost=nl2br($wallpost);应该完成任务。

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

在您最初的问题中,我认为存在一些混乱 - 用户不会每次想要新行时都键入'n。斜杠用于转义(特殊字符,不是普通的 n(。

在 Windows 计算机上,Enter 键等效于'r'n其中'r是回车符,'n是换行符。在 Linux 或类似设备上,Enter 键为 'n'r 的 ASCII 值是 13,'n 的 是 10。

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