Php custom truncation of Chinese strings-utf8 version,

Source: Internet
Author: User

Php custom truncation of Chinese strings-utf8 version,

Note: There are a lot of code for this problem on the Internet, but many of them are copied and pasted without practice, and the code has logic problems. The following code is compiled by myself.

Not much talk

/*** This function is for utf8 encoding * @ author 2582308253@qq.com * @ param string $ str * @ param int $ start * @ param int $ length * @ return string * @ copyright February 27, 2017 1:46:10 pm */function gbsubstr2 ($ str, $ start, $ length) {$ length = abs ($ length); $ strLen = strlen ($ str); $ len = $ start + $ length; $ newStr = ''; for ($ I = $ start; $ I <$ len & $ I <$ strLen; $ I ++) {if (ord (substr ($ str, $ I, 1)> 0xa0) {// a Chinese character in UTF-8 encoding occupies three bytes. For other encoded strings, Chinese characters occupy different bytes, you need to modify the number a $ newStr. = substr ($ str, $ I, 3); // here a = 3; $ I + = 2; $ len + = 2; // after intercepting three bytes, the end offset of the truncated string also needs to increase the A-1 with each Chinese Character truncation;} else {$ newStr. = substr ($ str, $ I, 1) ;}return $ newStr ;}

The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!

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.