PHP Custom Function Intercept Chinese character length example

Source: Internet
Author: User
    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. }
Copy Code

Call:

  1. $str = "This character is very long, ^_^";

  2. $Short _str=showshort ($STR, 4);//intercept the first 4 characters, 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. = "..."; To what end, modify here can be.

  31. return $tempstr;

  32. }

Copy Code

Here is a more concise way to intercept the length of Chinese characters:

    1. $len = 19;
    2. $text = "How will the long title of the news show only a few words in front, followed by ..." To replace it? ";
    3. echo strlen ($text) <= $len? $text: (substr ($text, 0, $len). chr (0). " ....");
Copy Code
  • Related Article

    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.