在PHP中移除换行并添加BR标签

3
我有以下文本需要在每个段落之间添加<br>标签,并删除所有换行符。我该如何在PHP中实现这一点?谢谢。
因此,这样 -
This is some text
for which I would
like to remove 
the line breaks.

And I would also 
like to place
a b>  tag after 
every paragraph.

Here is one more
paragraph.

Would become this -

This is some text for which I would like to remove the line breaks.<br/> And I would also like to place a br tag after every paragraph. <br> Here is one more paragraph.

注意:忽略任何字母的高亮显示。


你是故意使用了两种不同风格的 br 标签吗? - salathe
5个回答

7

好的,看起来你把段落分隔符视为空行。因此,最简单的解决方案似乎是这样的:

$text  = str_replace( "\r", "", $text ); // this removes the unwanted \r
$lines = explode( "\n", $text ); // split text into lines.
$textResult = "";
foreach( $lines AS $line )
{
   if( trim( $line ) == "" ) $textResult .= "<br />";
   $textResult .= " " . $line;
}

我认为这可以解决你的问题。$textResult会有你的结果。


+1 啊,终于有人讲道理了!我还没有测试过,所以最好能正常工作,否则我会回来的! - zaf

5
那也应该可以运行:(虽然有点简单)
$string = str_replace("\n\n", "<br />", $string);
$string = str_replace("\n", "", $string);

已经测试过了。


4

我可能漏掉了什么,或者没有人提供最简单的解决方案 -- 使用内建函数nl2br

echo nl2br($string);

请记住,如果您使用的是纯字符串(而不是变量)作为 nl2br 的参数,则必须使用双引号,否则您的控制字符,如 \ n 或 \ r 将不会被扩展。


0
echo str_replace(array("\n\n", "\n"), array("<br/>", " "), $subject);

上述代码将双换行符替换为<br/>标签,并将任何剩余的单个换行符替换为空格(以避免原本仅由换行符分隔的单词相互碰撞)。

如果需要处理CRLF(Windows)样式的换行符,则需要稍微(但不是非常)更改方法。


这个似乎也是正确的,但我想您无法确定空行上是否有空格,或者是否有任何 \r 字符。 - Gabriel Poama-Neagra
@Gabriel:没错,我们只能根据提问者提供的信息尽力而为。 - salathe

0

我用这个就可以了

$string = ereg_replace( "\n", "<br/>", $string);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接