Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP replacing literal \r\n with <br/> (not replacing new lines)

Basically I have this script that I'm trying to replace the literal text \r\n with <br /> for proper formatting. I've tried nl2br() and it didn't replace the \r\n with <br />. Here's the code.

$title = isset($post[0]) ? $post[0] : false;
$body = isset($post[1]) ? preg_replace('#(\r|\r\n|\n)#', '<br/>', $post[1]) : false;
echo $title."<br/>".$body;  
like image 408
Joshwaa Avatar asked May 28 '11 13:05

Joshwaa


3 Answers

If it's displaying \r and \n in your html, that means that these are not newlines and line breaks, but escaped backslashes followed by an r or an n (\\r for example). You need to strip these slashes or update your regex to account for them.

like image 95
Explosion Pills Avatar answered Sep 21 '22 03:09

Explosion Pills


try the str_replace() function

$title = isset($post[0]) ? $post[0] : false;
$body = isset($post[1]) ? str_replace(array('\r\n', '\r', '\n'), '<br/>', $post[1]) : false;
echo $title."<br/>".$body;
like image 38
afarazit Avatar answered Sep 21 '22 03:09

afarazit


$body = isset($post[1]) ? preg_replace('#(\\\r|\\\r\\\n|\\\n)#', '<br/>', $post[1]) : false;

You'll need three \\\. Inside single quotes, \\ translates to \ so \\\r becomes \\r which gets fed to the preg_replace funciton.

PREG engine has its own set of escape sequences and \r is one of them which means ASCII character #13. To tell PREG engine to search for the literal \r, you need to pass the string \\r which needs to be escaped once more since you have it inside single quotes.

like image 37
Salman A Avatar answered Sep 24 '22 03:09

Salman A