Home >Backend Development >PHP Tutorial >How to get which character appears most often in a string

How to get which character appears most often in a string

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-25 09:01:571119browse
How to get which character appears most often in a stringReprint address: http://blog.qita.in/?post=467
  1. $str=”asdfgfdas323344##$$fdsdfg*$**$*$**$$443563536254fas”;//Any length string
  2. //Solution one (the fastest solution, but the basic skills must be solid )
  3. $arr=str_split($str);
  4. $arr=array_count_values($arr);
  5. arsort($arr);
  6. print_r($arr);
  7. //Solution 2 (certain requirements for logical ability)
  8. $arr=str_split($str);
  9. $con=array();
  10. foreach ($arr as $v){
  11. if (!@$con[$v]){
  12. @$con[$v]=1 ;
  13. }else{
  14. @$con[$v]++;
  15. }
  16. }
  17. arsort($con);
  18. print_r($con);
  19. //Solution 3
  20. $arr=str_split($str);
  21. $unique=array_unique($arr);
  22. foreach ($unique as $a){
  23. $arr2[$a]=substr_count($str, $a);
  24. }
  25. arsort($arr2);
  26. print_r($arr2 );
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