我有以下文字,我希望在每个段落之间添加<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.
会成为这个 -
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.
注意:忽略任何字母的突出显示。
答案 0 :(得分: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 :(得分:5)
这也应该有效:(虽然过于简单)
$string = str_replace("\n\n", "<br />", $string);
$string = str_replace("\n", "", $string);
经过测试。
答案 2 :(得分:3)
要么我缺少某些内容,要么没有人能够提供最简单的解决方案 - 内置函数nl2br
:
echo nl2br($string);
只记得,如果你使用纯字符串(不是变量)作为nl2br
的参数,你必须使用双引号或你的控制字符,如\n
或{{1不会被扩展。
答案 3 :(得分:0)
echo str_replace(array("\n\n", "\n"), array("<br/>", " "), $subject);
上面将带有<br/>
标记的双重换行符和任何剩余的单个换行符替换为空格(以避免最初仅由换行符分隔的单词相互竞争)。
你是否需要迎合CRLF(windows)风格的换行符;这会稍微(虽然不是很大)改变方法。
答案 4 :(得分:0)
这适合我
$string = ereg_replace( "\n", "<br/>", $string);