Home > Backend Development > PHP Tutorial > 见见有没有更好的法子

见见有没有更好的法子

WBOY
Release: 2016-06-13 12:06:16
Original
873 people have browsed it

看看有没有更好的法子
刚在技术群看到一条N个钟前的问题:
用PHP如何找出在一个字符串中出现最多的字符

我的思路是先将字符串侵害成数组,通过array_count_values得到元素个数统计,排序,取最顶那个为最多次数,然后可能有多个相同最多次数,for循环找出来..

<br />$testStr = 'rewruo ewjrewm' . PHP_EOL . 'hcywer国bg gfaaf d中国国国s国rew';<br />$testStr = preg_replace('/\s/', '', $testStr);<br />preg_match_all('/./u', $testStr, $strList);<br />$charCount = array_count_values($strList[0]);<br />arsort($charCount);<br />$maxCount = current($charCount);<br />foreach($charCount as $char => $count){<br />	if($count < $maxCount){<br />		break;<br />	}<br />	echo $char . '出现了 ' . $count . ' 次<br />';<br />}<br />
Copy after login

------解决方案--------------------
已经没有都少简化的余地了
$testStr = 'rewruo ewjrewm' . PHP_EOL . 'hcywer国bg gfaaf d中国国国s国rew';<br />$testStr = preg_replace('/\s/', '', $testStr);<br />preg_match_all('/./u', $testStr, $strList);<br />$strList = array_count_values($strList[0]);<br />$r = array_keys($strList, $m = max($strList));<br />echo join($t=" 出现了 $m 次<br />", $r).$t;<br />
Copy after login
r 出现了 5 次
e 出现了 5 次
w 出现了 5 次
国 出现了 5 次

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template