I have a form with a <textarea>
and I want to capture any line breaks in that textarea on the server-side, and replace them with a <br/>
.
Is that possible?
I tried setting white-space:pre
on the textarea
's CSS, but it's still not enough.
I have a form with a <textarea>
and I want to capture any line breaks in that textarea on the server-side, and replace them with a <br/>
.
Is that possible?
I tried setting white-space:pre
on the textarea
's CSS, but it's still not enough.
If you're going to use
str_replace
orpreg_replace
, you should probably place the"\r\n"
at the beginning of the array, otherwise a\r\n
sequence will be translated into two<br/>
tags (since the\r
will be matched, and then the\n
will be matched).eg:
or
The
nl2br()
function exists to do exactly this:However, this function adds br tags but does not actually remove the new lines - this usually isn't an issue, but if you want to completely strip them and catch carriage returns as well, you should use a
str_replace
orpreg_replace
I think str_replace would be slightly faster but I have not benchmarked;
or
Have a look at the
nl2br()
function. It should do exactly what you want.For those wanting an answer that does not rely on
nl2br()
:or (in this case):
PHP Side: from Textarea string to PHP string
PHP Side: PHP string back to TextArea string: