2010-03-20 57 views
-1

有人可以幫忙嗎?php查找發生次數(次數)

我需要下面的函數來做到這一點...

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

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

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

將有什麼不同? – Val

回答

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

不是因爲,它會返回$ x = A6B2,這與$ x ='A4B1A2'不一樣。 – Val