php查找出现次数(次数)

时间:2010-03-20 13:57:28

标签: php numbers

有人可以帮忙吗?

我需要以下功能来执行此操作...

$x = 'AAAABAA';
$x2 = 'ABBBAA';

function foo($str){
   //do something here....
   return $str;
}

$x3 = foo($x); //output: A4B1A2
$x4 = foo($x2);//output: A1B3A2

2 个答案:

答案 0 :(得分:2)

substr_count是你的朋友

或者更确切地说是

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;
}

答案 1 :(得分:1)

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 "";
}