Php 删除多个空白

Php 删除多个空白,php,removing-whitespace,Php,Removing Whitespace,所以,如果我有一根像 "hello what is my name" 如何获取所有空间并仅用一个空间替换每个空间?找到了解决方案: <?php $str = ' This is a test '; $count = 1; while($count) $str = str_replace(' ', ' ', $str, $count); ?> 这应该可以做到: $replaced = preg_replace('/\s\s+/', '

所以,如果我有一根像

"hello    what is  my    name"
如何获取所有空间并仅用一个空间替换每个空间?

找到了解决方案:

<?php

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

?>

这应该可以做到:

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

hello what is my name

试试这个:-

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

这并不是最优雅的解决方案。。。事实上,它效率很低。对于不熟悉正则表达式的人来说,这是一个很好的解决方案。“效率”在这里并不重要。哇,回顾几年前我吸得有多糟很有趣。哇,回顾五年前我认为自己吸得有多烂很有趣,考虑到当时我仍然吸得有多烂。