views:

63

answers:

2

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?

Thanks!

A: 

Found the solution:

<?php

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

?>
ThinkingInBits
That's not really the most elegant solution... infact it's quite inefficient.
webdestroya
Good solution for one who aren't familiar with regular expressions. And "efficiency" doesn't really matter here.
Col. Shrapnel
+2  A: 

This should do it:

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

Output:

hello what is my name
Web Logic