刚在技术群看到一条N个钟前的问题:
用PHP如何找出在一个字符串中出现最多的字符
我的思路是先将字符串侵害成数组,通过array_count_values得到元素个数统计,排序,取最顶那个为最多次数,然后可能有多个相同最多次数,for循环找出来..
$testStr = 'rewruo ewjrewm' . PHP_EOL . 'hcywer国bg gfaaf d中国国国s国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 . '出现了 ' . $count . ' 次<br />';
}
------解决方案--------------------
已经没有都少简化的余地了
$testStr = 'rewruo ewjrewm' . PHP_EOL . 'hcywer国bg gfaaf d中国国国s国rew';r 出现了 5 次
$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 次<br />", $r).$t;
e 出现了 5 次
w 出现了 5 次
国 出现了 5 次