17

So, If I have a string like

"hello    what is  my    name"

How can I take all of the spaces and replace each with only one space?

4

3 回答 3

46

This should do it:

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

Output:

hello what is my name
于 2010-05-22T05:21:13.740 回答
3

Found the solution:

<?php

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

?>
于 2010-05-22T05:19:35.287 回答
2

尝试这个:-

$desc = "hello    what is  my    name";
echo trim(preg_replace('/\s+/', ' ', $desc));
于 2019-12-16T07:23:05.740 回答