如何从字符串中删除不必要的空格,以使HTML中没有额外的空格。

4
如何从字符串中删除不必要的空格,以便在HTML中没有额外的空格??
我从数据库中获取字符串,现在我正在尝试做以下操作:
nl2br(trim(preg_replace('/(\r?\n){3,}/', '$1$1', $comment->text)));

但它一直显示为这样: enter image description here 我需要得到完美的结果: enter image description here 怎么做呢?因为我对正则表达式不熟悉 :(
编辑: $comment->text 包含来自数据库的文本: enter image description here

1
$comment->text 包含什么内容?你能发布 var_dump($comment->text); 的输出吗? - Amal Murali
Amal Murali,我已经编辑了问题。 - Silverfall05
请在浏览器的页面源代码中显示 var_dump($comment->text) 的输出,而不是在浏览器或数据库客户端中呈现,这样我们就可以看到字符串长度和所有空格保持不变。 - Michael Berkowski
你能展示一下你的HTML源码吗?我有点困惑,因为浏览器在渲染数据时已经自动折叠了空格。除非你是在谈论由盒模型控制的垂直空间,否则我不确定为什么需要这些操作。 - JohnFx
正如我在图片中标记的那样,是的,我想要去掉垂直空间。 - Silverfall05
请查看页面源代码,而不是您在图像中使用的DOM检查器呈现的内容。DOM检查器会对重新组织空格进行各种操作,因为它的目的是查看DOM树,而不是源代码。在大多数浏览器中,使用Ctl-U或Option-U查看源代码... - Michael Berkowski
4个回答

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

输出

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

preg_replace('/(\r)|(\n)/', '<br>', $comment->text); 这就是我想要的 :) - Silverfall05
啊,对不起,我误解了问题 :) - Artas
@AigarsCibuļskis请注意,如果您的换行符类似于\r\n,或者输入字符串中有多个\n\r,那么这将产生一个接一个的<br>标签。 - Carlos

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"

0
使用简单的CSS。

p.a {
  white-space: nowrap;
}
<p class="a">
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
</p>


0

如果你只想删除空格,你可以使用这个 str_replace 函数。

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

或者如果你想要移除所有的空格,可以使用这个方法

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接