tags:

views:

57

answers:

2

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

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

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;
}
stereofrog
not really because, it will return $x = A6B2, which is not the same as $x = 'A4B1A2';
Val
see update.....
stereofrog
+1  A: 
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 "";
}
Michael