This article mainly introduces PHP's method of counting the number of occurrences of all characters in a string, involving operating techniques related to PHP character traversal and statistical operations. Friends in need can refer to the following
The examples in this article are described PHP implements a method to count the number of occurrences of all characters in a string. Share it with everyone for your reference, the details are as follows:
Let’s take a look at the effect first:
Algorithm:
Loop through the string once ($str
in this example) and record the strings that have appeared in an array (such as this In the example $strRecord
), if this recording function already exists, it will not be recorded;
is used to compare each string with the value of the record array (in this example $strRecord[]['key']
), if a value in the record is the same as this string, record the number of times + 1 ($strRecord[]['count in this example ']
);
Of course, set a variable, the default is false (such as $found
in this example), record each comparison, if the record array already has this value , set it to true, and use this tag to record the array that has not been encountered into the array
Implementation code:
<?php //统计字符串中出现的字符,出现次数 echo '<pre class="brush:php;toolbar:false">'; $str = 'aaabbccqqwweedfghhjffffffffggggggggg';//字符串示例 echo $str.'<br/>'; $strRecord=array();//把出现过的字符记录在此数组中,如果记录有,则不记录, for($i=0;$i<strlen($str);$i++){ $found = 0;//默认设置为没有遇到过 foreach((array)$strRecord as $k=>$v){ if($str[$i] == $v['key']){ $strRecord[$k]['count'] += 1;//已经遇到,count + 1; $found = 1;//设置已经遇到过的,标记 continue;//如果已经遇到,不用再循环记录数组了,继续下一个字符串比较 } } if(!$found){ $strRecord[] = array('key'=>$str[$i],'count'=>1);//记录没有遇到过的字符串 } } print_r($strRecord); ?>
The above is the detailed content of PHP method to count the number of occurrences of all characters in a string. For more information, please follow other related articles on the PHP Chinese website!