Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing duplicate characters next to each other [duplicate]

Tags:

string

php

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

like image 640
Steve Avatar asked Apr 26 '12 22:04

Steve


2 Answers

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, ','));
like image 82
Paul Avatar answered Sep 20 '22 15:09

Paul


$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
like image 42
Irfy Avatar answered Sep 21 '22 15:09

Irfy