如何检查字符串中字符的总出现次数

时间:2015-01-08 07:16:45

标签: php string

我想找出字符串中特定字符的总出现次数  我的代码是:

  $str = 'aabbbcccccaa';

  for ($i=0;$i<strlen($str);$i++){
    $len = 0;
    for ($j=$i;$j<=strlen($str);$j++){
        if($str[$i] == $str[$j]){
        $len++;
        }
    }
    echo "\n".$str[$i].' len is '.$len;
}

我的输出如下:

  a len is 4
  a len is 3
  b len is 3
  b len is 2
  b len is 1
  c len is 5
  c len is 4
  c len is 3
  c len is 2
  c len is 1
  a len is 2
  a len is 1

但我想要像:

  a len is 4
  b len is 3
  c len is 5 only 

我怎样才能做到这一点?

4 个答案:

答案 0 :(得分:3)

<强> RTM

<?php
$data = "Two Ts and one F.";

foreach (count_chars($data, 1) as $i => $val) {
   echo "There were $val instance(s) of \"" , chr($i) , "\" in the string.\n";
}
?>

答案 1 :(得分:1)

您应该使用substr_count()。它就在手册中:

http://php.net/manual/en/function.substr-count.php

或者count_chars()对于通用解决方案会更好:

http://php.net/manual/en/function.count-chars.php

在创建自己的东西之前,请务必查看手册..那里可能有一个功能完全符合您的要求..

答案 2 :(得分:0)

$str = 'aabbbcccccaa';

foreach (count_chars($str, 1) as $i => $val) {
   echo  chr($i), " len is $val " , "<br>";
}

答案 3 :(得分:0)

您好简单实施以下方式!

我们的自定义功能:

function count_chars_unicode($str, $x = false) {
    $tmp = preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY);
    foreach ($tmp as $c) {
        $chr[$c] = isset($chr[$c]) ? $chr[$c] + 1 : 1;
    }
    return is_bool($x)
        ? ($x ? $chr : count($chr))
        : $chr[$x];
}

用法:

print_r(count_chars_unicode('aabbbcccccaa', true));

O / P

数组([a] =&gt; 4 [b] =&gt; 3 [c] =&gt; 5)

print_r(count_chars_unicode('aabbbcccccaa', 'a'));  // frequency of "a"

O / P:4

print_r(count_chars_unicode('aabbbcccccaa'));  // count of uniq chars

O / P:3