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.
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?
You are storing the literal value of \r\n
in your database, not the actual characters they represent.
Verify this in your database. If you see \r\n
in the description field, then you're probably escaping the backslash when you're storing the data.
It looks like your text contains the individual characters \
, r
, \
, and n
, and does not contain actual newline characters. As such, str_replace()
should get the job done:
echo str_replace('\r\n', '<br>', $description);
The nl2br can take a second (optional) argument for "is_xhtml" which will convert the \r\n
into a <br>
for you. Just change your line to:
echo nl2br($description, TRUE);
来源:https://stackoverflow.com/questions/5226617/how-to-use-nl2br-to-handle-string-with-r-n