How to use nl2br () to process a string using '\ r \ n'?

I retrieve the value of the product description stored in the database from admin via textarea after the form is submitted. When I select a description from the database, I get $description = $row['description'];it and I would like the echo $ description on the main page to look like this: echo nl2br($description);but I see characters "\r\n"instead of creating new lines. From what I found here and on the web, your string should be used between double quotes, for example:

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

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

echo nl2br($description);

What br does not do, it infers \r\n. So what can I do, I cannot use double quotes here, in my experience.

+3
source share
4 answers

You can translate them into appropriate escape sequences before passing a string through nl2br(), for example:

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

But what are the literal adaptations in your database in the first place?

+6
source

You store the literal value \r\nin your database, not the actual characters that they represent.

Confirm this in your database. If you see \r\nin the description field, then you probably avoid backslashes when you store data.

+1
source

, \, r, \ n . , str_replace() :

echo str_replace('\r\n', '<br>', $description);
0

nl2br can take the second (optional) argument for "is_xhtml", which will convert \r\nto <br>for you. Just change your line to:

echo nl2br($description, TRUE);
-2
source

All Articles