3

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.

kenorb
  • 155,785
  • 88
  • 678
  • 743
Manny Calavera
  • 6,815
  • 20
  • 60
  • 85

4 Answers4

6

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?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • How should I handle $_POST['description'] upon database inserting in order to keep new lines intact ? Thanks. – Manny Calavera Mar 08 '11 at 00:00
  • @Manny Calavera: If you're not already using a textarea, you should use that. If you want to ensure `\r\n` always becomes a real newline, I guess you can simply run `str_replace()` before inserting, so you don't have to do it after fetching. – BoltClock Mar 08 '11 at 00:35
1

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.

kenorb
  • 155,785
  • 88
  • 678
  • 743
Dimitry
  • 6,545
  • 2
  • 20
  • 21
0

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);
kenorb
  • 155,785
  • 88
  • 678
  • 743
mfonda
  • 7,873
  • 1
  • 26
  • 30
-2

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);
alex
  • 479,566
  • 201
  • 878
  • 984
1tiger1
  • 67
  • 2