Detect a carriage return/new line in a text area with PHP
How do I de开发者_JS百科tect 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.
There's a php constant for this:
When do I use the PHP constant "PHP_EOL"?
Also look into nl2br()
.
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
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.
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!
You may use nl2br(). Please note that it will convert \n
and \r\n
to <br />\n
.
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.
Try this:
$text_area = str_replace(PHP_EOL,'<br/>', $text_area);
Using str_replace
精彩评论