代码之家  ›  专栏  ›  技术社区  ›  Val

php查找发生次数(次)

  •  -1
  • Val  · 技术社区  · 15 年前

    有人能帮忙吗?

    我需要以下函数来执行此操作…

    $x = 'AAAABAA';
    $x2 = 'ABBBAA';
    
    function foo($str){
       //do something here....
       return $str;
    }
    
    $x3 = foo($x); //output: A4B1A2
    $x4 = foo($x2);//output: A1B3A2
    
    2 回复  |  直到 15 年前
        1
  •  1
  •   froogz3301    15 年前
    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
  •  2
  •   user187291    15 年前

    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;
    }
    
    推荐文章