15

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 />
halfer
  • 19,824
  • 17
  • 99
  • 186
sebb
  • 187
  • 1
  • 1
  • 5
  • To make you understand, your working example DO NOT convert \r\n to `
    ` tag. But it's going in 2 steps: double quoted string converts \r\n sequence to new-line, carriage-return symbols, and then nl2br() function adds this tag to them (leaving these symbols intact). if you add `echo $mystring;` to your code you will see no \r\n\ printed
    – Your Common Sense Aug 17 '10 at 04:29

12 Answers12

36

try this:

echo preg_replace('/\v+|\\\r\\\n/Ui','<br/>',$row["comments"]);
Ivijan Stefan Stipić
  • 6,249
  • 6
  • 45
  • 78
bcosca
  • 17,371
  • 5
  • 40
  • 51
  • 1
    excellent approach. and then another one for output in plain text. I can't believe there are too many direct-minded people around, who can't move a step aside from what they read. "Answer question as it phrased and never think of it's background" - a real SO motto. No matter if an answer is actually a disservice. – Your Common Sense Aug 17 '10 at 04:24
  • I would suggest replacing \v+|\\\r\\\n first to get those line-endings (Mac/most Unix) and replacing any remaining \\\n for the remaining line endings. The regular expression you have listed will insert double the amount of line breaks for Mac/most Unix. Otherwise, this answers sebb's question. – greg Oct 04 '10 at 22:12
  • I change this for preg_replace('/\v+|\\\r\\\n/','
    ', $string), I was obtaining double
    s
    – netadictos May 09 '13 at 19:10
  • @netadictos is right, better use his code ( stillstanding maybe you could edit your answer? ) – Toni Michel Caubet Sep 26 '16 at 10:39
17

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

Community
  • 1
  • 1
DangerPaws
  • 765
  • 1
  • 7
  • 21
  • 2
    Thanks for posting. I found that nl2br wasn't working for me in a PHP script (nor in a Smarty template) until I first called stripcslashes. – w5m May 27 '16 at 13:57
8

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.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • 1
    You're not answering the question. Maybe he has no control over how the data get's into his database? Either way, it's in there now. Fixing code which is senselessly sanitizing his data will not help his problem. – blockhead Aug 17 '10 at 12:14
  • that's simple, dude. Not every question deserves an answer. – Your Common Sense Aug 17 '10 at 12:21
  • Sharpnel HI, thanks for the tip, youre right in my code I was doing escaping twice inadvertently , Im trying to understand , what is the process that happens when you escape twice? can you show me so i understand what happens to data when you escape twice? thanks – sebb Aug 17 '10 at 17:54
5

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

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

bhushya
  • 1,317
  • 1
  • 19
  • 33
4

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?

Christian Mann
  • 8,030
  • 5
  • 41
  • 51
2

Make sure that you are not to using strings from file and/or set in single apostrophe. Because string is treated literally, and nl2br will not work. NL2BR will work with double apostrophe.

halfer
  • 19,824
  • 17
  • 99
  • 186
Gzom
  • 21
  • 1
1

Data you have stored is allready added the slashes.

You have to use stripslashes() first then str_replace()

stripslashes(str_replace('\r\n','<br/>',$row["comments"]))
Dinesh Patil
  • 1,042
  • 10
  • 13
1

Building on what Christian is saying, why don't you trying replacing the literal '\r\n' with "\r\n"?

blockhead
  • 9,655
  • 3
  • 43
  • 69
1

For some reason this didn't work for me...

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

But this did...

$comments = stripcslashes($row["comments"]);

$commentsWithBreaks = nl2br($comments);

echo $commentsWithBreaks;
JamieTom
  • 101
  • 2
  • 14
0

Not working for me either. I just did the following:

$mensaje = str_replace("&#10;", "<br/>", $mensaje);

jdisla
  • 139
  • 6
0

I was able to replace newline with <br> using this code :

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

(windows machine)

Tamim
  • 916
  • 11
  • 19
0

This could be a solution, at least it was for me.

$message = str_replace("\\r\\n", "<br>", $message);

It is possible that you are getting a string in which the slashes are escaped (i.e. \\) and nl2br works with \n\r not \\n\\r

Once you understand this, the solution is easy :)

Utsav Barnwal
  • 985
  • 11
  • 14