10

How can I replace all commas followed by spaces (", ") with just commas (",")?

I don't want to replace spaces when they don't have a comma in front of them (" ").

2
  • please give example of your code Dec 5, 2019 at 16:52
  • 8 year later? Seriously?
    – Philip
    Dec 9, 2019 at 18:36

4 Answers 4

18

All the str_replace solutions will work. If you want to replace all whitespaces before and after the commas

$str = 'cat,  dog , cow,       horse   ,mouse,moose';

$pattern = '/\s*,\s*/';
$replace = ',';
$str = preg_replace($pattern, $replace, $str);
1
6

This should do the trick:

$str = "some, comma, seperated, words";
$str = str_replace(", ", ",", $str);
2

This will do the trick?

$sString = str_replace(", ", ",", $sString);
2

You can do:

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

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.