Try this:
$str = preg_replace('/,{2,}/', ',', trim($str, ','));
The trim
will remove starting and trailing commas, while the preg_replace
will remove duplicate ones.
Also, as @Spudley suggested, the regex /,{2,}/
could be replaced with /,,+/
and it would work too.
EDIT:
If there are spaces between commas, you may try adding the following line after the one above:
$str = implode(',', array_map('trim', explode(',', $str)))