删除彼此相邻的重复字符

im trying to remove duplicate characters that are directly next to each other

1,2,3,4,5 - has a few commas but they are not to be removed 1,,2,,3,,4,,5 - would have to be turned into the regular 1,2,3,4,5 no matter how many commas are inbetween each number i would like to have just one. i have something similar which makes sure there are no commas at the end of the string:

$n = "1,2,3,4,5";
for ($i=0;$i< strlen($n);$i++) {

    if (substr($n, -1) == ',') {
        $n = substr($n, 0, -1);
    }
}

would appreciate some help on this matter,

Thanks :)

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, ','));
$n = '1,2,,3,,,,,4,5';
$n = preg_replace('/(.)\\1+/', '$1', $n);

This should work for any duplicate characters immediately following one another.

However, it is unlikely that the asker wants to replace any character repetitions in this way (including numbers like 44 => 4). More likely, something like this is intended:

$n = preg_replace('/([,.;])\\1+/', '$1', $n); # replace repetitions of ,.:
$n = preg_replace('/([^\d])\\1+/', '$1', $n); # replace repetitions of non-digit characters