Php计算字符串唯一且出现的char

时间:2014-08-30 08:33:22

标签: javascript php

我之前写过使用javascript计算客户端

这是我的功能

var check = {}, string = inputString, count = 0;
var occurrence;
$.each(string.split(''), function(){
    if(!check[this]){
        count++;
        check[this]=true;
})

上面的函数我用它来计算字符串中的数字出现次数

例如

number 1234 will return 4, as there are number 1,2,3 and 4
number 1233 will return 3, as the unique number are 1,2 and 3
number 1212 will return 2, as the unique number are 1 and 2

我想知道如何将上面的函数转换为返回相同计数的工作php函数。

接下来是我写了另一张检查,即getMostOccurrence

目的是例如

number 1212, will return 2, as 1 appear 2 times, and 2 appear 2 times

但是如果数字

1112, the result will be 3, as 1 appear 3 times

我如何在php中执行此计数功能

感谢您的帮助!!

1 个答案:

答案 0 :(得分:2)

使用 count_chars

  

计算字符串中每个字节值(0..255)的出现次数,并以各种方式返回它。

直接来自 PHP.net

的示例
<?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";
}
?> 

您也可以非常轻松地使用它来实现您的第二个目的。