can someone help with this?
I need the following function to do this...
$x = 'AAAABAA';
$x2 = 'ABBBAA';
function foo($str){
//do something here....
return $str;
}
开发者_如何学JAVA
$x3 = foo($x); //output: A4B1A2
$x4 = foo($x2);//output: A1B3A2
substr_count is your friend
or rather this
function foo($str) {
$out = '';
preg_match_all('~(.)\1*~', $str, $m, PREG_SET_ORDER);
foreach($m as $p) $out .= $p[1] . strlen($p[0]);
return $out;
}
function foo($str) {
$s = str_split($str);
if (sizeof($s) > 0) {
$current = $s[0];
$output = $current;
$count = 0;
foreach ($s as $char) {
if ($char != $current ) {
$output .= $count;
$current = $char;
$output .= $current;
$count = 1;
}
else {
$count++;
}
}
$output .= $count;
return $output;
}
else
return "";
}
精彩评论