'ZZYYYYXXXWWVZZ'
指示输出:'3Z4Y3X2W1V2Z'
我尝试过的编码输出为:5Z4Y3X2W1V<?php $str = "zzzyyyyxxxwwvzz"; $strArray = count_chars($str, 1); foreach ($strArray as $key => $value) { echo $value.chr($key); } ?>
函数,在阵列中获取给定字符串中的所有字符使用
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;
preg_replace_callback()
是用于计数连续重复字符并将计数注入就位的直接工具。 demo$str = "zzzyyyyxxxwwvzz";
echo preg_replace_callback(
'/(.)\1*/',
fn($m) => strlen($m[0]) . $m[1],
$str
);
// 3z4y3x2w1v2z