移除多余的空格

21
所以,如果我有一个字符串像

这样的话
"hello    what is  my    name"

我该如何将所有空格取代为一个空格?

3个回答

51

这应该可以解决问题:

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

输出:

hello what is my name

3

找到了解决方案:

<?php

$str = ' This is    a    test   ';
$count = 1;
while($count)
    $str = str_replace('  ', ' ', $str, $count);

?>

6
那其实不是最优雅的解决方案...事实上,它相当低效。 - Mitch Dempsey
对于不熟悉正则表达式的人来说,这是一个很好的解决方案。而且,“效率”在这里并不是真正重要的。 - Your Common Sense
7
哇,回顾多年前自己的糟糕表现,感觉很有趣。 - ThinkingInBits
4
哇,回顾五年前的自己,我觉得自己很烂,而考虑到那个时候我还是非常地烂,真的很有趣。 - ThinkingInBits

2

试试这个:

$desc = "hello    what is  my    name";
echo trim(preg_replace('/\s+/', ' ', $desc));

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