[英]Remove line breaks and add BR tags in PHP
我有以下文本,我想在每個段落之間添加一個<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.
注意:忽略任何字母的突出顯示。
好吧,似乎你考慮一個段落分隔符,一個空行。 所以最簡單的解決方案似乎如下:
$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
會有你的結果
這應該也有效:(雖然過於簡單化)
$string = str_replace("\n\n", "<br />", $string);
$string = str_replace("\n", "", $string);
它經過測試。
要么我缺少某些東西,要么沒有人給出最簡單的解決方案 - 內置函數nl2br
:
echo nl2br($string);
只記得,如果你使用純字符串(不是變量)作為nl2br
的參數,你必須使用雙引號,否則你的控制字符,如\\n
或\\r
將不會被展開。
這對我來說
$string = ereg_replace( "\\n", "<br/>", $string);
echo str_replace(array("\n\n", "\n"), array("<br/>", " "), $subject);
上面將帶有<br/>
標簽的雙重換行符和任何剩余的單個換行符替換為空格(以避免最初僅由換行符分隔的單詞相互碰撞)。
你有沒有需要迎合CRLF(窗戶)風格的換行; 這會稍微(雖然不是很大)改變方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.