The three methods in php count the number of each character in a string and sort it
- 2020-05-19 04:26:28
- OfStack
<?php
// This method is purely a back function, no explanation;
function countStr($str){
$str_array=str_split($str);
$str_array=array_count_values($str_array);
arsort($str_array);
return $str_array;
}
// Here are some examples;
$str="asdfgfdas323344##$\$fdsdfg*$**$*$**$$443563536254fas";
print_r(countStr($str));
?>
<?
// This method has some data structure ideas, but it's easy to understand :)
function countStr2($str){
$str_array=str_split($str);
$result_array=array();
foreach($str_array as $value){// To determine if the character is a new type, set it to 1 If not, then add;
if(!$result_array[$value]){
$result_array[$value]=1;
}else{
$result_array[$value]++;
}
}
arsort($result_array);
return $result_array;
}
$str="asdfgfdas323344##$\$fdsdfg*$**$*$**$$443563536254fas";
var_dump(countStr2($str))
?>
<?php
// This method is purely a solution 1 The crappy version, first find all the characters of the total class, then in 1 a 1 with substr_count Functional statistics.
function countStr3($str){
$str_array=str_split($str);
$unique=array_unique($str_array);
foreach ($unique as $v){
$result_array[$v]=substr_count($str,$v);
}
arsort($result_array);
return $result_array;
}
$str="asdfgfdas323344##$\$fdsdfg*$**$*$**$$443563536254fas";
var_dump(countStr3($str));
?>
* no matter which method you use, you need to use str_split function, so this function is very important