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.
To preserve line breaks when getting text from a textarea with JavaScript, we can replace whitespace characters with '<br>\n' .
Talking specifically about textareas in web forms, for all textareas, on all platforms, \r\n will work.
To add a line break to your HTML code, you use the <br> tag. The <br> tag does not have an end tag. You can also add additional lines between paragraphs by using the <br> tags. Each <br> tag you enter creates another blank line.
To create a multi-line text input, use the HTML <textarea> tag. You can set the size of a text area using the cols and rows attributes. It is used within a form, to allow users to input text over multiple rows.
Have a look at the nl2br()
function. It should do exactly what you want.
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
or preg_replace
I think str_replace would be slightly faster but I have not benchmarked;
$val = str_replace( array("\n","\r","\r\n"), '<br />', $val );
or
$val = preg_replace( "#\n|\r|\r\n#", '<br />', $val );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With