重复重复字符,重复数量,然后是字符

问题描述 投票:0回答:2
EX输入:

'ZZYYYYXXXWWVZZ'

指示输出:'3Z4Y3X2W1V2Z'

我尝试过的编码
<?php $str = "zzzyyyyxxxwwvzz"; $strArray = count_chars($str, 1); foreach ($strArray as $key => $value) { echo $value.chr($key); } ?>

输出为:5Z4Y3X2W1V

	

使用

STR_SPLIT
函数,在阵列中获取给定字符串中的所有字符
php string replace character counting
2个回答
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;
  • RextesterDemo

preg_replace_callback()
是用于计数连续重复字符并将计数注入就位的直接工具。 demo

$str = "zzzyyyyxxxwwvzz"; echo preg_replace_callback( '/(.)\1*/', fn($m) => strlen($m[0]) . $m[1], $str ); // 3z4y3x2w1v2z


0
投票

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.