Home  >  Article  >  php教程  >  php中计算未知长度的字符串哪个字符出现的次数最多的代码

php中计算未知长度的字符串哪个字符出现的次数最多的代码

WBOY
WBOYOriginal
2016-06-06 20:41:14698browse

php中计算未知长度的字符串哪个字符出现的次数最多的代码,需要的朋友可以参考下

用到的函数:
str_split:把字符串分割到数组中。类似的函数explode() 函数把字符串分割为数组。array_count_values:用于统计数组中所有值出现的次数。
arsort:对数组进行逆向排序并保持索引关系。
主要用于对那些单元顺序很重要的结合数组进行排序。$str="asdfgfdas323344##$\$fdsdfg*$**$*$**$$443563536254fas";//任意长度字符串
复制代码 代码如下:
$arr=str_split($str);
$arr=array_count_values($arr);
arsort($arr);
print_r($arr);

输出:
复制代码 代码如下:
Array
(
[$] => 7
[3] => 6
[*] => 6
[4] => 5
[f] => 5
[s] => 4
[d] => 4
[5] => 3
[a] => 3
[6] => 2
[2] => 2
[g] => 2
[#] => 2
)

第二种方法:
用到的函数:
array_unique:删除数组中重复的值。substr_count:计算子串在字符串中出现的次数。
复制代码 代码如下:
$str="asdfgfdas323344##$\$fdsdfg*$**$*$**$$443563536254fas";//任意长度字符串
$arr=str_split($str);
$unique=array_unique($arr);
foreach ($unique as $a){
$arr2[$a]=substr_count($str, $a);
}
arsort($arr2);
print_r($arr2);
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn