PHP用一个HTML Break替换双行 [英] PHP replace double-lines with one HTML Break
问题描述
我正在使用< BR>
标签替换我的服务器上的所有\\\
\\\
,以便单个\\\
不会变为< BR>
。
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>
.
示例:
Hello,\n\nThis is an\nexample.\n\nThanks!
转到:
Hello,<BR>This is an\nexample,<BR>Thanks!
(注意单个\\\
未被替换)
(notice the single \n was not replaced)
当我在PHP中执行以下操作时,它不会用中断替换两行:
When I do the following in PHP, it does not replace the two lines with a break:
$str = str_replace("\n\n", "<br />", $str);
推荐答案
您的 \\\
实际上是
\r\\\
(这意味着输入来自Windows操作系统),我建议你将换行符归一化到* nix标准首先使用以下正则表达式:
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);
然后,您的原始代码段将工作( demo ):
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);
但是,如果输入来自Linux或旧的Mac OS(仅使用 \r
)。
But that wouldn't work if the input came from Linux or a old Mac OS (which only uses \r
).
这篇关于PHP用一个HTML Break替换双行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!