连续出现字符

时间:2018-09-26 07:33:51

标签: php string function character

连续出现的字符数,然后是字符

外部输入:'zzzyyyyxxxwwvzz'

  

预期输出:“ 3z4y3x2w1v2z”

我尝试过的代码

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

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

输出为:5z4y3x2w1v

1 个答案:

答案 0 :(得分:1)

  • 使用str_split函数,获取数组中给定字符串中的所有字符
  • 现在,使用基本循环和条件并存储前一个字符,您可以确定是否连续,并相应地生成生成的输出字符串。

尝试以下操作(在代码注释中进行解释):

$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