Analysis of PHP mb_strwidth problems in actual use

Source: Internet
Author: User

The news section of a recently developed PHP website project requires a function to extract strings Based on the title width and add "... ", the first thought is to use the PHP mb_string function implementation, mb_strimwidth, mb_strwidth, and then found that if the title contains the" "symbol, PHP mb_strwidth considers this symbol as one width. I wonder if this is not a Chinese Double quotation mark. It should be a byte in width, and the length should be two widths, after the query "" unicode respectively u201C and u201D, not in the range of Chinese characters, and then query the unicode.org code table, found that u2000-u206F is the range of universal symbols, although the characters in this range are all in the form of wide characters, the mb _ function of PHP considers it to be 1 width, and there is no way but to rely on your own.

The following functions are implemented:

 
 
  1. Function truncString ($ str, $ length)
  2. {
  3. $ CountLen = 0;
  4. For ($ I = 0; $ I <mb_strlen ($ str); $ I ++)
  5. {
  6. $ CountLen + = amb_strwidth (mb_substr ($ str, $ I, 1 ));
  7. If ($ countLen> $ length)
  8. Return mb_substr ($ str, 0, $ I );
  9. }
  10. Return $ str;
  11. }
  12. Function amb_strwidth ($ str_width)
  13. {
  14. $ Count = 0;
  15. For ($ I = 0; $ I <mb_strlen ($ str_width); $ I ++)
  16. {
  17. // If (mb_substr ($ str_width, $ I, 1) = "xE2x80x9C" | mb_substr ($ str_width, $ I, 1) = 'xe2x80x9d ')
  18. // If characters in the u2000-u206F are encountered, the counter is added to 2
  19. If (preg_match ("/[x {2000}-x {206F}]/u", mb_substr ($ str_width, $ I, 1 )))
  20. $ Count + = 2;
  21. Else
  22. $ Count + = mb_strwidth (mb_substr ($ str_width, $ I, 1 ));
  23. }
  24. Return $ count;
  25. }

The above is the specific solution to the problem when using PHP mb_strwidth. I hope it will help you.


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.