Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing linebreaks (newline,linefeed) characters in a textarea

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.

like image 821
lock Avatar asked Nov 14 '08 03:11

lock


People also ask

How do I preserve line breaks in textarea?

To preserve line breaks when getting text from a textarea with JavaScript, we can replace whitespace characters with '<br>\n' .

Which character defines a new line in the textarea?

Talking specifically about textareas in web forms, for all textareas, on all platforms, \r\n will work.

How do you add a new line character in HTML?

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.

How do I create a multi line textarea?

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.


2 Answers

Have a look at the nl2br() function. It should do exactly what you want.

like image 89
Marc Avatar answered Oct 16 '22 08:10

Marc


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 );
like image 25
Law Avatar answered Oct 16 '22 06:10

Law