Home  >  Article  >  Backend Development  >  PHP code to calculate the most frequent characters in a string of unknown length

PHP code to calculate the most frequent characters in a string of unknown length

WBOY
WBOYOriginal
2016-07-25 09:05:18835browse
  1. $arr=str_split($str);
  2. $arr=array_count_values($arr);
  3. arsort($arr);
  4. print_r($arr);
  5. ?>
Copy code

Output: Array ( [$] => 7 [3] => 6

  • => 6 [4] => 5 [f] => 5 => 4 [d] => 4 [5] => 3 [a] => 3 [6] => 2 [2] => 2 [g] => 2 [#] => 2 )

    Method 2: Functions used: array_unique: Remove duplicate values ​​from the array. substr_count: Count the number of times a substring appears in a string.

    1. $str="asdfgfdas323344##$$fdsdfg*$**$*$**$$443563536254fas";//Any length string
    2. $arr=str_split($str );
    3. $unique=array_unique($arr);
    4. foreach ($unique as $a){
    5. $arr2[$a]=substr_count($str, $a);
    6. }
    7. arsort($arr2);
    8. print_r ($arr2);
    9. ?>
    Copy code


  • 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