I have found many examples of how to find repeat characters in a string. I believe my requirement is unique.
I have string
$string=aabbbccffffd;
Based on georg's great point, I would use a regex. This will handle split duplicates like ddaaffffd
with array keys dd=>2
and ffffd=>3
but will only show one entry for dd
when given ddaadd
. To represent both would require a more complex array:
$string = "ddaabbbccffffda";
preg_match_all('/(.)\1+/', $string, $matches);
$result = array_combine($matches[0], array_map('strlen', $matches[0]));
arsort($result);
If you only need a count of ALL occurrences try:
$result = array_count_values(str_split($string));
arsort($result);
If you don't have split duplicates:
$string = 'aabbbccffffd';
$letters = str_split($string);
$result = array_fill_keys($letters, 1);
$previous = '';
foreach($letters as $letter) {
if($letter == $previous) {
$result[$letter]++;
}
$previous = $letter;
}
arsort($result);
print_r($result);
Or for a regex approach:
preg_match_all('/(.)\1+/', $string, $matches);
$result = array_combine($matches[1], array_map('strlen', $matches[0]));
arsort($result);