How to remove a character repeated in sequence?

6

How do I remove the repeated characters in sequence with PHP?

Entry:

  

Ellizabetth

Output:

  

Elizabeth

    
asked by anonymous 10.08.2016 / 21:06

2 answers

9

You can use preg_replace , an example:

$var = 'Elliiiiiiiiiiizabetth';
$pattern = '/(.)+/';
$replace = '$1';
$resultado = preg_replace($pattern, $replace, $var);
echo $resultado;

Result:

Elizabeth

Another example, on a single line, with the same result:

echo preg_replace('/(.)+/', '$1', 'Elliiiiiiiiiiizabetth');
    
10.08.2016 / 21:10
5

Another alternative is:

function unique($palavra){
    $p = str_split($palavra);
    return implode(array_map(function ($c) use ($p) { 
                      return ($c > 0 && $p[$c] == $p[$c - 1] ? '': $p[$c]); 
    }, array_keys($p)));
}


echo unique("Banana") . "\n";        // Banana
echo unique("Arara") . "\n";         // Arara
echo unique("assassinos") . "\n";    // asasinos
echo unique("Marreco") . "\n";       // Mareco
echo unique("Elllizabettth") . "\n"; // Elizabeth
echo unique("FooBaaar") . "\n";      // FoBar
echo unique("Woow") . "\n";          // Wow
echo unique("baazz") . "\n";         // baz

View demonstração

A second alternative is to go through the string in a loop for and check that the current letter equals the previous letter:

function unique2($palavra){
    $ret = "";

    for ($i = 0; $i < strlen($palavra); $i++){
        if ($i == 0 || $palavra[$i] != $palavra[$i - 1]) $ret .= $palavra[$i];
    }
    return $ret;
}

echo unique2("Banana") . "\n";        // Banana
echo unique2("Arara") . "\n";         // Arara
echo unique2("assassinos") . "\n";    // asasinos
echo unique2("Marreco") . "\n";       // Mareco
echo unique2("Elllizabettth") . "\n"; // Elizabeth
echo unique2("FooBaaar") . "\n";      // FoBar
echo unique2("Woow") . "\n";          // Wow
echo unique2("baazz") . "\n";         // baz

View demonstração

Note

Both functions are case-sensitive , that is, it differs from uppercase and lowercase, so use function strtolower " in both letters that will be compared, or make the comparison using function strcasecmp .

    
10.08.2016 / 21:43