如何使用 php 实现 php 字符计数:输入:bbbvvvvzzxxc输出:3b4v2z2xc我尝试这个代码:$str = "aabbbccaaaac";$arr1 = str_split($str);$count=1;foreach($arr1 as $key=>$char) { if($key==0){ $pre=$char; } if($pre==$char){ $count++; } else{ $count=1; $pre=$char; }echo $pre.'---'.$char.'__'; if($pre != $char){ echo $char. $count ; } else { // echo $char; } }但不工作:设置字符数很简单
1 回答
喵喵时光机
TA贡献1846条经验 获得超7个赞
$str = "aabbbccaaaac";
$arr1 = str_split($str);
$count=0;
$pre = '';
$result = ''; // our result string
foreach($arr1 as $char){
if($char == $pre){
$count++;
}else{
if($count > 0){ // To check whether it was the first iteration
$result .= $count.$pre;
}
$count = 1;
$pre = $char;
}
}
$result .= $count.$pre; // For last iteration
echo $result;
- 1 回答
- 0 关注
- 88 浏览
添加回答
举报
0/150
提交
取消