开发者

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

开发者 https://www.devze.com 2023-03-08 19:04 出处:网络
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\

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;  


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


You could try this:

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


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;


As I read the comments of the question I would suggest to try following code:

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


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]?

0

精彩评论

暂无评论...
验证码 换一张
取 消