Php code for retrieving the substrings that appear most frequently in a Chinese string
- /***
- ** The length of a substring can be customized, for example, four consecutive characters.
- ** Site http://bbs.it-home.org
- $ Str = 'I am a chinese, I am a foreigner, I am a Korean, I am an American, I am a British, I am a chinese, I am a 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 );
- // Obtain the sub-string 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;
- }
- }
- // Process multiple results
- Foreach ($ str_arr as $ key => $ value)
- {
- If ($ value = $ cnt)
- {$ Str. = $ key ."
";}
- }
- The most frequently occurring substring of echo is:
'. $ Str .'
Number of occurrences: '. $ cnt;
- }
- ?>
If you are interested, you can also refer to this article: php calculates the code that contains the maximum number of characters in strings with unknown length. |