在PHP String中查找最常见的字符

时间:2018-04-18 15:34:33

标签: php

我正在寻找找到php字符串中最常见字符的最有效方法。

我有一个看起来像这样的字符串:

"aaaaabcaab"

结果应存储在变量$ total。

所以在这种情况下,$ total应该等于a

2 个答案:

答案 0 :(得分:1)

您可以使用此功能

function getHighest($str){
    $str = str_replace(' ', '', $str);//Trims all the spaces in the string
    $arr = str_split(count_chars($str.trim($str), 3));
    $hStr = "";
    $occ = 0;

    foreach ($arr as $value) {
        $oc = substr_count ($str, $value);
        if($occ < $oc){
            $hStr = $value;
            $occ = $oc;
        }
    }

    return $hStr;
}

答案 1 :(得分:1)

实现这一目标的最简单方法是:

// split the string per character and count the number of occurrences
$totals = array_count_values( str_split( 'fcaaaaabcaab' ) );

// sort the totals so that the most frequent letter is first
arsort( $totals );

// show which letter occurred the most frequently
echo array_keys( $totals )[0];

// output
a

要考虑的一件事是在出现平局时会发生什么:

// split the string per character and count the number of occurrences
$totals = array_count_values( str_split( 'paabb' ) );

// sort the totals so that the most frequent letter is first
arsort( $totals );

// show all letters and their frequency
print_r( $totals );

// output
Array
(
    [b] => 2
    [a] => 2
    [p] => 1
)