连续出现的字符数,然后是字符
外部输入:'zzzyyyyxxxwwvzz'
预期输出:“ 3z4y3x2w1v2z”
我尝试过的代码
<?php
$str = "zzzyyyyxxxwwvzz";
$strArray = count_chars($str,1);
foreach ($strArray as $key=>$value)
{
echo $value.chr($key);
}
?>
输出为:5z4y3x2w1v
答案 0 :(得分:1)
尝试以下操作(在代码注释中进行解释):
$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;