1

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?

4 Answers 4

3

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Regular expressions are always relatively slow, so whenever possible, it's best to use alternatives.
2

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

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

1 Comment

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!
1

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

4 Comments

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,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.
this doesn't work in my case because sometime there will be name like 'Jim Karry'. But thank you very much.
@esafwan,Sorry for that but then using space as separator may not be a good idea.
1

A non-regex approach:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.