Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nl2br not working for me

Tags:

php

I can't get nl2br function to work after fetching data from my database:

$result = mysql_query("SELECT comments..etc.etc..");

while ($row = mysql_fetch_array($result))
{
  echo nl2br($row["comments"]);
}

In database row comments:

\r\nThanks,\r\n

OUTPUT:

Same as in DB:

\r\nThanks,\r\n

If I simply test this out like so it works fine:

<?php
$mystring = "\r\nThanks,\r\n";
echo nl2br($mystring);
?>

OUTPUT:

converts \r \n to <br />
like image 867
sebb Avatar asked Aug 17 '10 02:08

sebb


5 Answers

Most likely you are doing escaping twice, when adding your data into DB.
Check your code that adds data to DB and remove unnecessary escaping.

Most likely it's some senseless "universal sanitization" function.

Well it's easy.
Let's take a quote, not a newline to demonstrate. The behavior the same. Slashes being stripped then data goes to database.

Thus, in the normal case:

source: It's
after escaping: It\'s
by the query execution slash being stripped and
both in the database and back It's

in double escaping case:

source: It's
after escaping: It\'s
after second escaping: It\\\'s
by the query execution slash being stripped and
both in the database and back It\'s
we have our data spoiled.

Just make yourself understand that escaping i not something magical that makes your data "safe" (and, therefore can be done many times, as you probably think). It's just adding a backslash to certain symbols.

like image 75
Your Common Sense Avatar answered Oct 23 '22 04:10

Your Common Sense


try this:

echo preg_replace('/\v+|\\\r\\\n/Ui','<br/>',$row["comments"]);
like image 31
bcosca Avatar answered Oct 23 '22 06:10

bcosca


I know this is an old post but if like me you are have stumbled across this issue and the above didn't work for you, this solution may help you instead:

echo nl2br(stripslashes($row["comments"]));

or (they are not the same function, note the additional "c" after strip)

echo nl2br(stripcslashes($row["comments"]));

See original thread that helped me: nl2br() not working when displaying SQL results

like image 22
DangerPaws Avatar answered Oct 23 '22 06:10

DangerPaws


My guess is that the slashes in your DB are literal slashes (followed by n or r), not newlines. Can you find a way to store literal newlines in your database?

like image 4
Christian Mann Avatar answered Oct 23 '22 06:10

Christian Mann


Following solution will work for both windows as well as for linux/unix machine

str_replace(array("\\r\\n", "\\r", "\\n"), "<br />", "string");

like image 4
bhushya Avatar answered Oct 23 '22 04:10

bhushya