Remove repeating character
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; $开发者_JAVA百科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
echo preg_replace("/(.)\\1+/", "$1", "cakkke");
Output:
cake
Explanation:
(.)
captures any character
\\1
is 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 $1
replaces the complete matched text kkk
in this case, with the first capture group, k
in this case.
You want to first match a character, followed by that character repeated: (.)\1+
. Replace that with the first character. The brackets create a backreference to the first character, which you use both to match the repeated instances and as the replacement text.
preg_replace('/(.)\1+/', '$1', $str);
精彩评论