Php code for retrieving the substrings that appear most frequently in a Chinese string

Source: Internet
Author: User
Php code for retrieving the substrings that appear most frequently in a Chinese string

  1. /***
  2. ** The length of a substring can be customized, for example, four consecutive characters.
  3. ** Site http://bbs.it-home.org
  4. $ 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 ';
  5. Count_string ($ str, 5 );
  6. Function Count_string ($ sstr, $ length)
  7. {
  8. $ Cnt_tmp = 0;
  9. $ Cnt = 0;
  10. $ Str = '';
  11. $ Str_tmp = array ();
  12. $ Str_arr = array ();
  13. Mb_internal_encoding ("gb2312 ");
  14. $ Max_length = (mb_strlen ($ sstr)-$ length );
  15. // Obtain the sub-string set
  16. For ($ I = 0; $ I <= $ max_length; $ I ++)
  17. {
  18. $ Str_tmp [] = mb_substr ($ sstr, $ I, $ length );
  19. }
  20. // Remove duplicate substrings
  21. $ Str_tmp = array_unique ($ str_tmp );
  22. // Calculate the number of occurrences
  23. Foreach ($ str_tmp as $ key => $ value)
  24. {
  25. $ Cnt_tmp = mb_substr_count ($ sstr, $ value );
  26. If ($ cnt_tmp >=$ cnt)
  27. {
  28. $ Cnt = $ cnt_tmp;
  29. $ Str_arr [$ value] = $ cnt;
  30. }
  31. }
  32. // Process multiple results
  33. Foreach ($ str_arr as $ key => $ value)
  34. {
  35. If ($ value = $ cnt)
  36. {$ Str. = $ key ."
    ";}
  37. }
  38. The most frequently occurring substring of echo is:
    '. $ Str .'
    Number of occurrences: '. $ cnt;
  39. }
  40. ?>

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.