PHP intercept Chinese characters (utf-8 format) functions

Source: Internet
Author: User
  1. /**

  2. @UTF-8 Chinese character truncation program
  3. @http://bbs.it-home.org
  4. */
  5. $STR = "321 This is the test string";
  6. $str 1 = "() ()";
  7. Echo subutf8str ($str, 0, 3). "
    ";
  8. Echo subutf8str ($str, 0,4). "
    ";
  9. Echo subutf8str ($str 1,0,4). "
    ";
  10. Echo subutf8str ($str 1,0,10). "
    ";

  11. function Subutf8str ($str, $start =0, $length =80) {

  12. $cur _len = 0; People understand the length of the string
  13. $all _len = strlen ($STR); Machine Understanding String Length
  14. if ($length > $all _len)
  15. {
  16. return $str;
  17. }
  18. for ($i = 0; $i < $all _len;)
  19. {
  20. if ($cur _len = = $start)
  21. {
  22. Break
  23. }
  24. if (Ord ($str [$i]) > 127)
  25. {
  26. $i + = 3;
  27. }else{
  28. $i + = 1;
  29. }
  30. $cur _len + +;
  31. }
  32. $start _pos = $i;
  33. $temp _pos = $cur _len;
  34. for (; $cur _len-$temp _pos < $length;)
  35. {
  36. if ($i >= $all _len)
  37. Break
  38. if (Ord ($str [$i]) > 127)
  39. {
  40. $i + = 3;
  41. }else{
  42. $i + = 1;
  43. }
  44. $cur _len + +;
  45. }
  46. $end _pos = $i;
  47. Return substr ($str, $start _pos, $end _pos);
  48. }
  49. ?>
Copy Code

PHP comes with a library of functions that deal with strings, it is recommended that we go into the study, a lot of practice.

  • 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.