views:

38

answers:

4

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?

+2  A: 

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

$str = preg_replace("/ *,+ */", " ", $str);
icktoofay
Answer by casablanca and this both are working well. But what will be the best thing to implement? Regex or the other one? Which one is fast? Thanx!
esafwan
+1  A: 

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

SpawnCxy
@downvoter,comments plz.
SpawnCxy
I think you got the downvotes because the code feels weird, namely the nesting of the second `str_replace`. Also, this function call results in more replaces, which has (albeit immaterial unless you're processing thousands of strings) performance implications.
Steven Xu
@Steven XU,acturally I do it like this to make it be able to handle more unknown situations,e.g,if OP has more than one space beside comma like `, `,` ,`,then it will still work.
SpawnCxy
this doesn't work in my case because sometime there will be name like 'Jim Karry'. But thank you very much.
esafwan
@esafwan,Sorry for that but then using space as separator may not be a good idea.
SpawnCxy
+1  A: 

A non-regex approach:

$str = str_replace(", ", ",", $str); # Remove single space after a comma
$str = implode(' ', explode(',',str));
Graphain
+3  A: 

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)

casablanca
the regex example by icktoofay is also giving the result. Which one is the best to used in terms of speed and performance?
esafwan
Regular expressions are always relatively slow, so whenever possible, it's best to use alternatives.
casablanca