How to use nl2br() to handle string with '\r\n'?

Manny Calavera picture Manny Calavera · Mar 8, 2011 · Viewed 11.5k times · Source

I am retrieving a product description value stored in database from admin through textarea upon form submit. When I select the description from database I get $description = $row['description']; and I would like to echo $description on main page like this: echo nl2br($description); but I see "\r\n" characters instead of making new rows. From what I've found here and on the net, your string must be used between double quotes, like this:

echo nl2br("Hello, \r\n This is the description");

Now, the value of $description from database is in fact "Hello, \r\n This is the description" but in my script I have to use it like this:

echo nl2br($description);

Which does not make br's, it is outputing \r\n instead. So, what can I do, I can't use double quotes here, from my experience.

Answer

BoltClock picture BoltClock · Mar 8, 2011

You could translate them into their respective escape sequences before passing the string through nl2br(), like this:

$description = nl2br(str_replace('\\r\\n', "\r\n", $description));

But what are the literal escapes doing in your database in the first place?