21

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?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
ThinkingInBits
  • 10,792
  • 8
  • 57
  • 82

3 Answers3

50

This should do it:

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

Output:

hello what is my name
3

Found the solution:

<?php

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

?>
ThinkingInBits
  • 10,792
  • 8
  • 57
  • 82
2

Try this:-

$desc = "hello    what is  my    name";
echo trim(preg_replace('/\s+/', ' ', $desc));
Paras Raiyani
  • 748
  • 5
  • 10