Replace carriage returns by email

I'm trying to replace carriage return with line break in PHP so that my site moderators don't enter
every time they want to add a new line when entering email from my site. I tried several different methods to replace line breaks, but none worked. Methods I tried:

preg_replace('/\r\n?/', "<br />", $str); eregi_replace(char(13), "<br />", $str); str_replace("\r\n", "<br />", $str); str_replace("\n", "<br />", $str); 

and nl2br functions.

I searched Google for about half an hour and found nothing. Can anyone help?

+1
source share
3 answers

Pretty good example from php.net documentation

 // Order of replacement $str = "Line 1\nLine 2\rLine 3\r\nLine 4\n"; $order = array("\r\n", "\n", "\r"); $replace = '<br />'; // Processes \r\n first so they aren't converted twice. $newstr = str_replace($order, $replace, $str); 
+2
source

Did you check it like that?

 $str = str_replace( "\r\n", "<br />", $str ); $str = str_replace( "\r", "<br />", $str ); $str = str_replace( "\n", "<br />", $str ); 

This should work almost always. And remember, always use "\r" instead of '\r' .

+1
source

Your regex eludes your r and n .

Instead

 preg_replace('/\r\n?/', "<br />", $str); 

Try the following:

 preg_replace('/\\r\\n/', "<br />", $str); 
+1
source

All Articles