Phpmb_strlen () Chinese/English mixed character truncation code

Source: Internet
Author: User
If a fatalerror: calltoundefinedfunctionmb_strlen occurs when using mb_strlen, you can use phpinfo () to check whether mbstring is loaded. if not, try to copy php_mbstringdll to the windows directory.

If fatal error: call to undefined function mb_strlen occurs when using mb_strlen, you can use php info () to check whether mbstring is loaded. if not, try to copy php_mbstring.dll to the windows directory.

Utf-8 file encoding

  1. $ Var = 'ABC ';
  2. Mb_strlen ($ var, 'utf-8'); // output 7. both Chinese and English occupies one byte.
  3. Mb_strlen ($ var); // output 15 Chinese characters in three bytes. English occupies one byte.
  4. Mb_strlen ($ var, 'gbk'); // output 9 is abnormal

Retrieve all Chinese characters

  1. Function utf8substr ($ str, $ from, $ len)
  2. {
  3. Return preg_replace ('# ^ (? : [X00-x7f] | [xc0-xff] [x80-xbf] +) {0, '. $ from .'}'.
  4. '((? : [X00-x7f] | [xc0-xff] [x80-xbf] +) {0, '. $ len.'}). * # s ',
  5. '$ 1', $ str );
  6. }

Intercept code between Chinese and English

  1. Function gb2312_strlen ($ string)
  2. {
  3. $ Str_len = strlen ($ string );
  4. $ Str_count = 0;
  5. For ($ j = 0; $ j <$ str_len; $ j ++)
  6. {
  7. If (ord ($ string {$ j}) <127)
  8. {
  9. $ Str_count + = 1;
  10. Continue;
  11. }
  12. Else
  13. {
  14. If (ord ($ string {$ j + 1})> 127)
  15. {
  16. $ Str_count + = 1;
  17. $ J ++;
  18. Continue;
  19. }
  20. Else
  21. {
  22. $ Str_count + = 1;
  23. Continue;
  24. }
  25. }
  26. }
  27. Return $ str_count;
  28. }
  29. $ Str = "enable s d ";
  30. Echo gb2312_strlen ($ str );

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.