如何在PHP中保留前端的额外空间?

时间:2016-11-09 10:18:48

标签: php html css

我有以下存储在数据库中的确切字符串:

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);显示此数据,然后保留段落换行符,但删除字符串中给出的额外空格。

我如何解决这个问题,请帮忙!

4 个答案:

答案 0 :(得分: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>';

答案 1 :(得分:0)

使用<pre><?= $val; ?></pre>标记包装来保留文本中的任何空格和新行。

答案 2 :(得分:0)

由于HTML的工作方式,空格已关闭。

保护它们的最佳方法是:

  1. &nbsp;替换空格。
    这是一个“非破坏空间”角色的HTML实体。它显示为空格,但被浏览器视为可打印字符。因此,它不会像普通空间那样被关闭。它还可以防止浏览器在那时进行自动换行,因此如果你想强迫单词在一起,它会很有用。

  2. 使用CSS white-space: pre; 这会强制浏览器停止关闭所有空格。它还会在您的文本中返回回车符,因此它几乎可以满足您的要求。它可能会对您的页面布局产生连锁效应。

  3. 其中任何一个都可以解决问题。但是,我会重复我在上面的评论中所说的内容 - 使用空格来操纵文本的格式几乎总是错误的解决方案。在十五年前,当IE6成为国王并且我们没有尽可能多的CSS功能可用时,它可能是正确的做法,但今天它几乎肯定不是正确的方法。

答案 3 :(得分:-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 );