Example of intercepting the length of a Chinese character using a php custom function

Source: Internet
Author: User
Example of intercepting the length of a Chinese character using a php custom function

  1. Function msubstr ($ str, $ start, $ len ){
  2. $ Strlen = $ start + $ len;
  3. For ($ I = 0; $ I <$ strlen; $ I ++ ){
  4. If (ord (substr ($ str, $ I, 1)> 0xa0 ){
  5. $ Tmpstr. = substr ($ str, $ I, 2 );
  6. $ I ++;
  7. } Else
  8. $ Tmpstr. = substr ($ str, $ I, 1 );
  9. }
  10. Return $ tmpstr;
  11. }

Call:

  1. $ Str = "this character is long ,''';

  2. $ Short_Str = showShort ($ str, 4); // extract the first four Chinese characters and the result is: this character...
  3. Echo "$ Short_Str ";
  4. Function csubstr ($ str, $ start, $ len)
  5. {
  6. $ Strlen = strlen ($ str );
  7. $ Clen = 0;
  8. For ($ I = 0; $ I <$ strlen; $ I ++, $ clen ++)
  9. {
  10. If ($ clen >=$ start + $ len)
  11. Break;
  12. If (ord (substr ($ str, $ I, 1)> 0xa0)
  13. {
  14. If ($ clen> = $ start)
  15. $ Tmpstr. = substr ($ str, $ I, 2 );
  16. $ I ++;
  17. } Bbs.it-home.org
  18. Else
  19. {
  20. If ($ clen> = $ start)
  21. $ Tmpstr. = substr ($ str, $ I, 1 );
  22. }
  23. }

  24. Return $ tmpstr;

  25. }
  26. Function showShort ($ str, $ len)
  27. {
  28. $ Tempstr = csubstr ($ str, 0, $ len );
  29. If ($ str <> $ tempstr)
  30. $ Tempstr. = "..."; // you can modify the description here.

  31. Return $ tempstr;

  32. }

Here is a more concise method for intercepting the length of Chinese characters:

  1. $ Len = 19;
  2. $ Text = "how to display only the first few words in a long news title, which is replaced? ";
  3. Echo strlen ($ text) <= $ len? $ Text: (substr ($ text, 0, $ len). chr (0 )."....");

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.