6

How do I detect a carriage return/new line character in a text area in PHP?

I want to replace them with <br /> tags before storing it in the database.

random
  • 9,774
  • 10
  • 66
  • 83
André Alçada Padez
  • 10,987
  • 24
  • 67
  • 120

7 Answers7

9

There's a php constant for this:

When do I use the PHP constant "PHP_EOL"?

Also look into nl2br().

Community
  • 1
  • 1
Denis de Bernardy
  • 75,850
  • 13
  • 131
  • 154
8

My advice: "don't do it". Just store the line breaks in the db, but render it to <br /> only when producing the output. Otherwise you'll have the problem of replacing the <br /> when you want to use that data in a different context.

For that, you can use nl2br See: http://php.net/manual/en/function.nl2br.php

Yoshi
  • 54,081
  • 14
  • 89
  • 103
4

I know this is v-old but just wanted to make a note here, perhaps even for myself! The eols here need to be in double quotes, otherwise It just won't work. See below...

$eols = array(",","\n","\r","\r\n");
$text_area = str_replace($eols,'<br />',$_POST['text_area']);

Hope this helps someone not waste time like I just did for 30mins!

Mike Wells
  • 414
  • 4
  • 14
4

Just nl2br it ;)

PS: Don't apply the function when inserting to the database (use only SQL escaping here). Apply the function as soon as you want to output the text to HTML.

NikiC
  • 100,734
  • 37
  • 191
  • 225
1

You may use nl2br(). Please note that it will convert \n and \r\n to <br />\n.

Paolo Stefan
  • 10,112
  • 5
  • 45
  • 64
1

You can use the nl2br() function. This will insert <br/> as necessary.

It is generally my preference to leave the HTML formatting out of the DB (unless it was in the source material). You never know when you may want to use the clean version for other purposes.

Brad
  • 159,648
  • 54
  • 349
  • 530
-1

Try this:

$text_area = str_replace(PHP_EOL,'<br/>', $text_area);

Using str_replace

Naftali
  • 144,921
  • 39
  • 244
  • 303