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

2019-01-19 07:26发布

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.

标签: php mysql nl2br
4条回答
forever°为你锁心
2楼-- · 2019-01-19 07:46

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?

查看更多
We Are One
3楼-- · 2019-01-19 07:50

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);
查看更多
三岁会撩人
4楼-- · 2019-01-19 07:59

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);
查看更多
【Aperson】
5楼-- · 2019-01-19 08:05

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.

查看更多
登录 后发表回答