删除重复字符 [英] Remove repeating character
问题描述
我如何删除重复字符(例如,删除cakkkke
中的字母k
,使其成为cake
)?
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?
推荐答案
使用反向引用
echo preg_replace("/(.)\\1+/", "$1", "cakkke");
输出:
cake
说明:
(.)
捕获任何字符
\\1
是对第一个捕获组的反向引用.在这种情况下,上面的.
.
\\1
is a backreferences to the first capture group. The .
above in this case.
+
使后向引用至少匹配1(以便它匹配aa,aaa,aaaaa,但不匹配a)
+
makes the backreference match atleast 1 (so that it matches aa, aaa, aaaa, but not a)
用$1
替换它会在此情况下用第一个捕获组k
替换完全匹配的文本kkk
.
Replacing it with $1
replaces the complete matched text kkk
in this case, with the first capture group, k
in this case.
这篇关于删除重复字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!