2016-11-09 38 views
-1

我有以下存儲在數據庫中精確的字符串:如何在PHP中保留前端的額外空間?

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an       unknown printer took a galley of type and scrambled it      to make a type specimen book. 


It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. 

注意額外的空間和額外的段落/換行符我在字符串中增加了。

在PHP我顯示使用echo nl2br($val);那麼它保留了一段換行,但刪除字符串中給出的額外空間這個數據。

我怎樣才能解決這個問題,請大家幫忙!

+0

請參閱:http:// stackoverflow。com/q/2300142/3933332 – Rizier123

+2

對[tag:html]而言,這實際上比[tag:php]要多得多...... – deceze

+1

真正的問題是爲什麼你想要這樣做 - 如果你想要格式化文本通過放入大量空格,那麼你做錯了。由於HTML和CSS都提供了所有格式化功能,因此很少有很好的理由嘗試使用空格字符。你給出的例子顯然不是你想要達到的目標的準確表示,所以我很難進一步說出你應該怎麼做,但空間不是答案。 – Simba

回答

0

使用<pre><?= $val; ?></pre>標籤包裝保存在文本的任何空白和新線。

1

PHP不刪除空格。甚至沒有HTML。

但HTML壓緊兩個或多個連續的空格上渲染一個。因爲這是HTML的工作原理。

有幾種方式,迫使它呈現文本爲是。

其中之一是把文字變成<pre>元素:

echo '<pre>', $val, '</pre>'; // there is no need to nl2br() 

另一種方法是強制元素使用CSS屬性white-space渲染:

echo '<p style="white-space: pre;">', $val, '</p>'; 
+0

@deceze使用'echo()'函數有什麼問題? (除了連接字符串的性能損失之外,在大多數情況下並不算太多......) – axiac

+0

它本身沒有錯誤*,但它是多餘的。這就像在每個表達式('foo((((2 + 2))))')周圍添加多餘的括號。它沒有做任何事情,因此不應該被認爲是典型的代碼示例。 – deceze

+0

我不同意。當它們僅包含一條語句時,是否還將條件語句和循環中的大括號刪除?這種情況下的大括號是多餘的,不做任何事情,不是嗎? – axiac

-1

讓我們試着以下的代碼保留文本中的任何空格和新行。

$str = "<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an       unknown printer took a galley of type and scrambled it      to make a type specimen book.</p> 

<p>It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>"; 

echo preg_replace("/\r|\n/", "", $str); 
0

由於HTML的工作方式,空格被關閉。

保存它們的最好方法是:

  1. &nbsp;替換空間。
    這是一個'non-breaking space'字符的HTML實體。它顯示爲空格,但被瀏覽器視爲可打印的字符。因此,它不會像普通空間那樣封閉。它還可以防止瀏覽器在當時進行單詞換行,所以如果你想強迫單詞在一起,這很有用。

  2. 使用CSS white-space: pre;
    這會強制瀏覽器停止關閉所有空格。它還會在您的文本中帶回回車,所以它幾乎可以滿足您的要求。不過,它可能會對頁面佈局產生連鎖效應。

其中任何一個都可以實現。但是,我會重複上述評論中的內容 - 使用空格來操縱文本的格式幾乎總是錯誤的解決方案。在15年前,當IE6成爲國王,我們沒有儘可能多的CSS特性可供使用時,在某些情況下這可能是正確的做法,但是今天它幾乎肯定不是正確的做法。