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.
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.
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
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!
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.
You may use nl2br(). Please note that it will convert \n
and \r\n
to <br />\n
.