开发者

php find number of occurances (number of times)

开发者 https://www.devze.com 2022-12-24 02:34 出处:网络
can someone help with this? I need the following function to do this... $x = \'AAAABAA\'; $x2 = \'ABBBAA\';

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

精彩评论

暂无评论...
验证码 换一张
取 消