removing duplicate characters next to each other

listed in answer

removing duplicate characters next to each other
0 votes, 0.00 avg. rating (0% score)

ANSWER:

Looks like you only want to do this with commas, so it’s extremely easy to do with preg_replace:

$n = '1,2,,3,,,,,4,5';
$n = preg_replace('/,+/', ',', $n);     // $n == '1,2,3,4,5'

Also you can replace the code you gave above that makes sure there are no commas at the end of a string with rtrim. It will be faster and easier to read:

$n = '1,2,,3,4,5,,,,,'
rtrim($n, ',');                         // $n == '1,2,3,4,5'

You can combine them both into a one-liner:

$n = preg_replace('/,+/', ',', rtrim($n, ','));

by PaulP.R.O. from http://stackoverflow.com/questions/10342441