Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

php - 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; $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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...