Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
198 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...