Remove all spaces but leave 1 space each

$word="01 2  3   4    5     6      7        8         9          0'; 

I have a variable like the above.
and I like to remove all spaces between the numbers but leave 1 space between numbers if each has any space.
The following is the code I tried, but failed

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

it is still remained many spaces which is more than one space .

The result below is what I want.

01 2 3 4 5 6 7 8 9 0

http://php.net/preg-replace

As a test, try replacing the single space to be replaced with ‘X’ then echo the result.

Repeat until there are only single spaces and X showing.

From the echoed results a solution should be available.

while ( strstr($word, '  ') )
  $word = str_replace('  ', ' ', $word);
$word = preg_replace('/\s+/', ' ', $word);
2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.