Let's see if there is any better way. I just saw a problem N minutes ago in the technical group:
How to find the most common characters in a string using PHP?
My idea is to first break the string into an array and use array_count_values to get the number of elements for statistics, sorting, taking the top one as the maximum number of times, and then there may be multiple identical maximum times, find out the for loop ..
$ TestStr = 'fig '. PHP_EOL. 'hcywer country bg gfaaf d China country s country rew'; $ testStr = preg_replace ('/\ s/', '', $ testStr); preg_match_all ('/. /U', $ testStr, $ strList); $ charCount = array_count_values ($ strList [0]); arsort ($ charCount); $ maxCount = current ($ charCount ); foreach ($ charCount as $ char => $ count) {if ($ count <$ maxCount) {break;} echo $ char. 'appears '. $ count. times
';}
Reply to discussion (solution)
Since array_count_values is used, it is enough to use max to calculate the intersection.
If you use arsort, the echo key ($ charCount) is the most frequently used character.
Since array_count_values is used, it is enough to use max to calculate the intersection.
If you use arsort, the echo key ($ charCount) is the most frequently used character.
I cyclically output the characters that belong to the same maximum number of times. according to your practice, only one of them is output.
Since array_count_values is used, it is enough to use max to calculate the intersection.
If you use arsort, the echo key ($ charCount) is the most frequently used character.
I cyclically output the characters that belong to the same maximum number of times. according to your practice, only one of them is output.
Have you tried it? Intersection. array_intersect. First, try the result ~
Have you tried it? Intersection. array_intersect. First, try the result ~
Find the code. the result of my code is as follows:
R appears 5 times
W appears 5 times
5 times in China
E appears 5 times
Because there are four characters with the same number of times and the maximum number of times
There is no room for simplification.
$ TestStr = 'fig '. PHP_EOL. 'hcywer country bg gfaaf d China country s country rew'; $ testStr = preg_replace ('/\ s/', '', $ testStr); preg_match_all ('/. /U', $ testStr, $ strList); $ strList = array_count_values ($ strList [0]); $ r = array_keys ($ strList, $ m = max ($ strList); echo join ($ t = "$ m appears
", $ R). $ t;
R appears 5 times
E appears 5 times
W appears 5 times
5 times in China