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

18,279

Solution 1

$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.

Solution 2

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.

Solution 3

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;

Solution 4

You could try this:

$body = nl2br(strtr($post[1], array('\r' => chr(13), '\n' => chr(10))));

Solution 5

As @tandu mentioned if you're seeing \r or \n in the html then you need to use stripslashes() first before applying nl2br(). The slashes are automatically added if you're data is coming from a form.

So your code would become:

$title = isset($post[0]) ? nl2br(stripslashes($post[0])) : false;
$body = isset($post[1]) ? nl2br(stripslashes($post[1])) : false;
echo $title."<br/>".$body;

Hope that helps.

EDIT: Um..just another thought. Should you be using $_POST[0] and $_POST[1]?

Share:
18,279
Joshwaa
Author by

Joshwaa

Updated on June 06, 2022

Comments

  • Joshwaa
    Joshwaa about 2 years

    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;  
    
  • Joshwaa
    Joshwaa about 13 years
    It's working now. The code I'm using: $body = isset($post[1]) ? preg_replace('#(\\\r|\\\r\\\n|\\\n)#', '<br/>', $post[1]) : false;
  • Salman A
    Salman A about 13 years
    @Josh: I missed out the third slash before the last n. I've edited my answer.
  • Petr Peller
    Petr Peller about 13 years
    You should update your question with a sample of the input, so we can better find where is the problem.
  • cssyphus
    cssyphus over 8 years
    @FutureReaders See Explosion Pills answer below if getting \n in html text