2011-05-10 142 views
48

試圖簡單地替換一些新的行。已經嘗試了3種不同的方式,我沒有變化:如何用<br/>替換 r&n?

$description = preg_replace('/\r?\n|\r/','<br/>', $description); 
$description = str_replace(array("\r\n","\r","\n"),"<br/>", $description); 
$description = nl2br($description); 

這些都應該工作,但我仍然得到換行符。他們是雙重的:「\ r \ r」。這不應該使這些失敗的權利?

+1

爲什麼你裸'\ r'換行符? AFAIK甚至MacOSX切換到'\ n'。 – ThiefMaster 2011-05-10 06:36:37

+0

他們來自客戶的CSV。 – 2011-05-13 22:53:31

+0

[如何從字符串中刪除換行符(無字符!)的可能的重複?](http://stackoverflow.com/questions/10757671/how-to-remove-line-breaks-no-characters-from-the -string) – kenorb 2015-03-03 00:28:21

回答

91

已經有nl2br()功能取代插入之前<br>標籤換行字符:

例(codepad):

<?php 
// Won't work 
$desc = 'Line one\nline two'; 
// Should work 
$desc2 = "Line one\nline two"; 

echo nl2br($desc); 
echo '<br/>'; 
echo nl2br($desc2); 
?> 

但是,如果它仍然沒有工作,確保文字$desciption是雙引號。

這是因爲與雙引號字符串相比,單引號不會「擴大」轉義序列,如\n。從PHP文檔報價:

注意:當它們出現在單引號字符串特殊字符不像雙引號和定界符語法,變量和轉義序列不會被擴大。

+0

查看第3行。它不工作。 – 2011-05-10 06:36:43

+0

仔細一看,他的OP明確表示他們試圖使用'nl2br'並且它不起作用。 – 2011-05-10 06:38:45

+0

試圖用雙回車返回字符串上運行nl2br,它工作正常。 – Decko 2011-05-10 06:41:29

-2

如果您正在使用nl2br\n\r所有出現將被<br>被替換。但是,如果(我不知道是怎麼回事),你仍然可以得到新的線路,你可以使用

str_replace("\r","",$description); 
str_replace("\n","",$description); 

要由空字符串

+0

它們不是REPLACED – 2013-05-02 14:31:09

+0

'str_replace'中的'\ r'似乎取代了所有內容。此外,您應該用'
'替換它...... – 2014-08-11 00:14:54

5

nl2br()因爲你擁有它應該很好地工作replase不必要新行:

$description = nl2br($description); 

您的示例代碼的第一行未封閉的'更有可能導致您的問題。刪除'$後描述...

...$description'); 
49

嘗試使用此

$description = preg_replace("/\r\n|\r|\n/",'<br/>',$description); 
+7

更快的替代方案可以是$ description = str_replace([「\ r \ n」,「\ r」,「\ n」],「
」,$描述)'採取[這個答案](http://stackoverflow.com/a/20717751/2431281) – Keale 2015-07-29 09:33:21

+4

(也可以使用['/ \ R /'所有CR/LF](https:// nikic .github.io/2011/12/10/PCRE-and-newlines.html)linebreak組合。) – mario 2015-08-13 19:28:05

11

你可能有真正的字符 「\」 字符串中(單引號字符串,如說@Robik)。

如果您確定'\ r'或'\ n'字符串應該被替換,我不是在這裏談論特殊字符,而是兩個字符'\'和'r'的序列,然後逃避替換字符串中的「\」,它會工作:

str_replace(array("\r\n","\r","\n","\\r","\\n","\\r\\n"),"<br/>",$description); 
0

這將肯定工作:

str_replace("\\r","<br />",$description); 
str_replace("\\n","<br />",$description); 
+0

絕對不正確的建議。 「foo \\ r \\ nbar」將變成「foobar」而不是「foo
」。在替換html渲染之前「foo bar」。 – Artemix 2012-09-14 13:55:36

+0

呃。適用於輸入格式已知的特定情況。 – evandentremont 2013-05-06 14:48:39

2

nl2br()爲我工作,但我需要換用雙引號變量:

此作品:

$description = nl2br("$description"); 

這不起作用:

$description = nl2br($description); 
0

試試這個:

echo str_replace(array('\r\n','\n\r','\n','\r'), '<br>' , $description); 
+0

閱讀關於PHP [strings](http://php.net/manual/en/language.types.string.php)。 ['\ r \ n'](http://php.net/manual/en/language.types.string.php#language.types.string.syntax.single)與['「\ r \ n「個'](http://php.net/manual/en/language.types.string.php#language.types.string.syntax.double)。 – axiac 2018-02-22 10:05:25

+0

謝謝@axiac,我沒有時間測試,但你的意思是它應該是''\ r \ n「'對嗎? – l2aelba 2018-02-22 12:49:57

相關問題