How to remove a repeated character in sequence?

Asked

Viewed 1,023 times

6

How do I remove repeated characters in sequence with PHP?

Entree:

Ellizabetth

Exit:

Elizabeth

2 answers

9


You can use the preg_replace, an example:

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

Upshot:

Elizabeth

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

echo preg_replace('/(.)\1+/', '$1', 'Elliiiiiiiiiiizabetth');
  • 1

    If you’re using ' instead of " I see no reason to use \\ , can use '/(.)\1+/' or '/(.*)\1+/'. If you were using " should wear "/(.)\\1+/", with \\ . Either way, both work normally.

  • Inkeliz... grateful for the comment. I’ve adjusted on the question.

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

See demonstração

A second alternative is to walk the string in a loop for and check that the current letter is equal to 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

See demonstração

Note

Both functions are case-sensitive, that is, differs capital letters and minuscules, to solve this use the function strtolower in both letters that will be compared, or make the comparison using the function strcasecmp.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.