PHP Chinese string intercept function supports multiple encodings

Source: Internet
Author: User
  1. /*

  2. * @todo Chinese intercept, support GB2312,GBK,UTF-8,BIG5
  3. * @http://bbs.it-home.org
  4. * @param string $str the string to intercept
  5. * @param int $start intercept start position
  6. * @param int $length intercept length
  7. * @param string $charset UTF-8|GB2312|GBK|BIG5 encoding
  8. * @param $suffix whether to add suffix
  9. */

  10. function Csubstr ($str, $start =0, $length, $charset = "Utf-8", $suffix =true)

  11. {
  12. if (function_exists ("Mb_substr"))
  13. Return Mb_substr ($str, $start, $length, $charset);
  14. $re [' utf-8 '] = "/[\x01-\x7f]| [\XC2-\XDF] [\x80-\xbf]| [\xe0-\xef] [\X80-\XBF] {2}| [\xf0-\xff] [\X80-\XBF] {3}/";
  15. $re [' gb2312 '] = "/[\x01-\x7f]| [\xb0-\xf7] [\xa0-\xfe]/];
  16. $re [' gbk '] = "/[\x01-\x7f]| [\x81-\xfe] [\x40-\xfe]/];
  17. $re [' big5 '] = "/[\x01-\x7f]| [\x81-\xfe] ([\x40-\x7e]|\xa1-\xfe]) /";
  18. Preg_match_all ($re [$charset], $STR, $match);
  19. $slice = Join ("", Array_slice ($match [0], $start, $length));
  20. if ($suffix) return $slice. " ...";
  21. return $slice;
  22. }
  23. ?>
Copy Code

The above code, looking at the bull X, to know the PHP regular, that is pretty tough. Copy the above code, test it on your machine, and do more hands-on, helping to improve the programming level quickly.

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