views:

4777

answers:

4

errr i checked the related questions using different re-phrase(s) of my question but nothing was related enough to my question....
anyway i have this form with a <textarea> and i wanted to capture any line breaks in that textarea on server-side and replace them with a <br/> is that possible? i tried setting the css of the textarea to white-space:pre but its still not enough...

+10  A: 

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

http://ca3.php.net/manual/en/function.nl2br.php

Marc
thanks a lot+1 for ya^_^
lock
Glad I could help!
Marc
+1  A: 

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 );
Laura Williams
+1  A: 

If your going to use the str_replace or preg_replace, you should probably place the "\r\n" at the beginning of the array, otherwise a \r\n sequence will be translated into two
tags, since the \r will be matched, and then the \n will be matched.

eg:

$val = str_replace( array("\r\n", "\n","\r"), '<br />', $val );

or

$val = preg_replace( "#\r\n|\n|\r#", '<br />', $val );
A: 

Very thanks .... \o/

Sitthykun