问题
I am trying to replace all \n\n on my server with the <BR>
tag so that a single \n does not turn into <BR>
.
Example:
Hello,\n\nThis is an\nexample.\n\nThanks!
goes to:
Hello,<BR>This is an\nexample,<BR>Thanks!
(notice the single \n was not replaced)
When I do the following in PHP, it does not replace the two lines with a break:
$str = str_replace("\n\n", "<br />", $str);
回答1:
Your \n
are actually \r\n
(which means the input came from a Windows operating system), I suggest you normalize you newlines to the *nix standard first with the following regular expression:
$str = preg_replace('~\r\n?~', "\n", $str);
Then, your original snippet will work (demo):
$str = str_replace("\n\n", '<br />', $str);
You could also just do:
$str = str_replace("\r\n\r\n", '<br />', $str);
But that wouldn't work if the input came from Linux or a old Mac OS (which only uses \r
).
回答2:
You need to double escape your characters:
Try:
$str = str_replace("\\n\\n", "<br />", $str);
来源:https://stackoverflow.com/questions/10825380/php-replace-double-lines-with-one-html-break