2013-12-19 35 views
4

如何從字符串中刪除不必要的空格,所以HTML中沒有多餘的空格?如何從字符串中刪除不必要的空格,所以在HTML中沒有多餘的空格

即時得到來自DB和現在我試圖做類似的字符串:

nl2br(trim(preg_replace('/(\r?\n){3,}/', '$1$1', $comment->text))); 

但持續顯示這樣的:

enter image description here

我需要的是讓完美:

enter image description here

怎麼做?因爲我不擅長的正則表達式:(

編輯: $ comment->文本包含DB文本:

enter image description here

+1

什麼'$評論 - > TE xt'包含?你能發佈var_dump($ comment-> text)的輸出嗎? –

+0

Amal Murali,我編輯過問題 –

+0

請從瀏覽器的頁面源顯示'var_dump($ comment-> text)'的輸出,而不是在瀏覽器或數據庫客戶端中顯示,因此我們可以看到字符串長度和所有空白完好無損。 –

回答

1
preg_replace('/(\r)|(\n)/', '', $comment->text); 

輸出

"1 2"<br>"2 3"<br>"3"<br>"4"<br>"5" 
+0

preg_replace('/(\ r)|(\ n)/','
',$ comment-> text);這就是我想要的:) –

+0

啊對不起,我誤解了這個問題:) – Artas

+0

@AigarsCibuļskis請注意,如果你的行結束符如'\ r \ n'或者你有多個輸入字符串中的\ n或'\ r'。 – Carlos

0

如果要刪除剛剛的空間你可以使用這個str_replace函數

$string = str_replace(' ', '', $string); 

,或者如果你想刪除所有whitespeces使用

$string = preg_replace('/\s+/', '', $string); 
0

這工作得很好,也避免了彼此跟隨多個<br>標籤:

$string = '12 
23 
3 
4 
5 
6'; 

var_dump(implode("\n<br>\n", preg_split('/(\r?\n)+/', $string))); 

var_dump(preg_replace('/(\r?\n)+/', "\n<br>\n", $string)); 

輸出:

string(38) "12 
<br> 
23 
<br> 
3 
<br> 
4 
<br> 
5 
<br> 
6" 

string(38) "12 
<br> 
23 
<br> 
3 
<br> 
4 
<br> 
5 
<br> 
6" 
相關問題