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;
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.
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;
$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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With