converting csv string to a string with spaces instead of commas in php

I'm having a string which is comma seperated like this

$str = "john, alice, mary,joy";

Some are having space after comma and some don't. What I want to do is remove all the commas and make them like this:

$str = "john alic mary joy";

What is the best way to do this in php?


str_replace is the simplest solution when there is at most one space after the comma:

$str = str_replace(array(', ', ','), ' ', $str);

If there can be multiple spaces, then I would go with the regex solution. (see icktoofay's answer)

Although regular expressions may not be the best way, a simple regular expression such as this could transform that data:

$str = preg_replace("/ *,+ */", " ", $str);

echo str_replace(',',' ',str_replace(' ','',$str));

A non-regex approach:

$str = str_replace(", ", ",", $str); # Remove single space after a comma
$str = implode(' ', explode(',',str));

Need Your Help

Sticky Footer doesn't work well on Safari and Chrome

jquery html css sticky-footer

What can be happening in this case ? It's a very nice .NET website, but when I check the website in Safari or chrome, sometimes the footer doesnt work well, and I have to scroll the page (move the ...