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


How to preserve extra spaces on front-end in 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);显示此数据,然后它保留段落换行符,但删除字符串中给出的额外空格。

我怎么能解决这个问题,请帮助!

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>';

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

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

保存它们的最好方法是:

  1. &nbsp;代替空格
    这是一个用于"不换行空格"字符的HTML实体。它显示为一个空格,但被浏览器视为一个可打印的字符。因此它不会像普通空间那样闭合。它还可以防止浏览器在此时换行,所以如果你想强制单词在一起,它很有用。

  2. 使用CSS white-space: pre; .
    这将强制浏览器停止关闭所有空格。它还带回文本中的回车符,它基本上满足了你的要求。它可以对你的页面布局产生连锁反应。

这两种方法都可以。然而,我要重申我在上面的评论中所说的——使用空格来操纵文本格式几乎总是错误的解决方案。15年前,当IE6为王的时候,我们没有那么多的CSS特性可以使用,在某些情况下,这可能是正确的做法,但今天,这几乎肯定不是正确的方法。

让我们试试下面的代码将保留文本中的空白和新行。

$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 );