How would I remove repeating characters (e.g. remove the letter k in cakkkke for it to be cake)?
One straightforward way to do this would be to loop through each character of the string and append each character of the string to a new string if the character isn’t a repeat of the previous character.
Here is some code that can do this:
$newString = '';
$oldString = 'cakkkke';
$lastCharacter = '';
for ($i = 0; $i < strlen($oldString); $i++) {
if ($oldString[$i] !== $lastCharacter) {
$newString .= $oldString[$i];
}
$lastCharacter = $oldString[$i];
}
echo $newString;
Is there a way to do the same thing more concisely using regex or built-in functions?
Use backrefrences
Output:
Explanation:
(.)captures any character\\1is a backreferences to the first capture group. The.above in this case.+makes the backreference match atleast 1 (so that it matches aa, aaa, aaaa, but not a)Replacing it with
$1replaces the complete matched textkkkin this case, with the first capture group,kin this case.