PHP replace double-lines with one HTML Break

二次信任 提交于 2019-12-11 02:43:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!