Replace commas followed by spaces with commas

2019-01-24 09:11发布

问题:

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 (" ").

回答1:

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);


回答2:

This should do the trick:

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


回答3:

This will do the trick?

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


回答4:

You can do:

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