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?
In Excel, there are several ways to filter for unique values—or remove duplicate values: To filter for unique values, click Data > Sort & Filter > Advanced. To remove duplicate values, click Data > Data Tools > Remove Duplicates.
1) Sort the elements. 2) Now in a loop, remove duplicates by comparing the current character with previous character. 3) Remove extra characters at the end of the resultant string.
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.
Use this regex "(.)\\1+" and replace with $1.
Don't really know php, but in C#:
Console.WriteLine(Regex.Replace("cakkkkeee", "(.)\\1+", "$1"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With