How do I remove the repeated characters in sequence with PHP?
Entry:
Ellizabetth
Output:
Elizabeth
How do I remove the repeated characters in sequence with PHP?
Entry:
Ellizabetth
Output:
Elizabeth
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');
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
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
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
.