-
- /***
- **The length of the substring can be customized, such as 4 consecutive characters
- **site http://bbs.it-home.org
- $str =' I am Chinese I am foreigner I am Korean I am American I am Chinese I am British I am Chinese I am foreigner';
- Count_string($str,5);
- function Count_string($sstr, $length)
- {
- $cnt_tmp = 0;
- $cnt = 0;
- $str = '';
- $str_tmp = array();
- $str_arr = array();
- mb_internal_encoding("gb2312");
- $ max_length = (mb_strlen($sstr)-$length);
-
- //Get the substring set
- for($i=0;$i<=$max_length;$i++)
- {
- $str_tmp[] = mb_substr($ sstr, $i, $length);
- }
- //Remove duplicate substrings
- $str_tmp = array_unique($str_tmp);
-
- //Calculate the number of occurrences
- foreach($str_tmp as $key=>$value)
- {
- $cnt_tmp = mb_substr_count($sstr,$value);
- if($cnt_tmp>=$cnt)
- {
- $cnt = $cnt_tmp;
- $str_arr[$value] = $cnt;
- }
- }
-
- //Handle multiple results
- foreach($str_arr as $key=>$value)
- {
- if($value == $cnt)
- {$str .=$key."
";}
- }
-
- echo 'The most frequently occurring substring is:
'.$str.' Number of occurrences:'.$cnt;
- }
- ?>
-
Copy code
Yes Interested friends can also refer to this article: php calculates the code for the most frequent characters in a string of unknown length.
|