Replace commas followed by spaces with commas

Philip picture Philip · Jun 9, 2011 · Viewed 11.7k times · Source

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

Answer

David Chan picture David Chan · Jun 9, 2011

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