phpstringreplacecharactercounting

Replace consecutive repeated characters with the number of repetitions followed by the character


number of consecutive occurrence of character followed by character

Ex input : 'zzzyyyyxxxwwvzz'

expected output : '3z4y3x2w1v2z'

code that I have tried

<?php
$str = "zzzyyyyxxxwwvzz";
$strArray = count_chars($str, 1);

foreach ($strArray as $key => $value)
{
    echo $value.chr($key);
}
?>

output is : 5z4y3x2w1v


Solution

  • Try the following (explanation in code comments):

    $input = 'zzzyyyyxxxwwvzz';
    
    // Split full string into array of single characters
    $input_chars = str_split($input);
    
    // initialize some temp variables
    $prev_char = '';
    $consecutive_count = 0;
    
    $output = '';
    
    // Loop over the characters
    foreach ($input_chars as $char) {
    
        // first time initialize the previous character
        if ( empty($prev_char) ) {
            $prev_char = $char;
            $consecutive_count++;
        } elseif ($prev_char === $char) { // current character matches previous character
            $consecutive_count++;
        } else { // not consecutive character
            // add to output string
            $output .= ($consecutive_count . $prev_char);
    
            // set current char as new previous_char
            $prev_char = $char;
            $consecutive_count = 1;
        }
    }
    
    // handle remaining characters
    $output .= ($consecutive_count . $prev_char);
    echo $output;
    

    Rextester Demo