Determine repeat characters in a php string

后端 未结 5 1199
星月不相逢
星月不相逢 2021-01-16 23:48

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;
         


        
5条回答
  •  南笙
    南笙 (楼主)
    2021-01-17 00:20

    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);
    

    Legacy Answers:

    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);
    

提交回复
热议问题