nl2br() not working when displaying SQL results

廉价感情. 提交于 2020-01-05 08:39:33

问题


On my Joomla module, we are using the following code to get shouts from the database

function getShouts($number, $timezone, $message) {
    $shouts = array();
    $db = JFactory::getDBO();
    $query = $db->getQuery(true);
    $query->select('*')
    ->from('#__shoutbox')
    ->order('id DESC');
    $db->setQuery($query , 0 , $number);
    $rows = $db->loadObjectList();
    $i=0;
    foreach ( $rows as $row ) {
        $shouts[$i]->id = $row->id;
        $shouts[$i]->name = $row->name;
        $shouts[$i]->msg = $row->msg;
        $i++;
    }
    return $shouts;
}

and the following code to display it in the default.php

print stripslashes($shouts[$i]->msg);

However this is causing problems when someone wants to input something like the following:

test line 1
test line 2

If they go onto a new line, the post displays like so after being submitted:

test line 1rntest line 2

So I did some research and realised I had to use nl2br() which I did as shown below:

print stripslashes(nl2br($shouts[$i]->msg));

however, it didn't seem to resolve the issue. I also tried creating another function in the helper to replace it using preg_replace but this didn't help either.

Can anyone explain why line breaking isn't working after adding nl2br() and how to fix it?


回答1:


Try this way:

print nl2br(stripcslashes($shouts[$i]->msg));

Pay attention to the stripcslashes() function, but not stripslashes()

Or just:

print nl2br($shouts[$i]->msg);

UPD: nl2br() function replaces \n with <br />. The problem is that you don't have \n in your text, but have n or \\n. I think there is no need to use stripslashes() when you get data from base, except the situation when you have ecranized data in your base.



来源:https://stackoverflow.com/questions/13410105/nl2br-not-working-when-displaying-sql-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!