Php custom truncation of Chinese Strings-utf8

Source: Internet
Author: User
This article mainly introduces the php custom method for intercepting Chinese strings, which has good reference value. let's take a look at the following below: There are a lot of code for this problem on the Internet, however, many of them are copy and paste, but they do not have their own practices, 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 ;}

For more articles about customizing and intercepting a Chinese string in php-utf8, refer to the PHP Chinese website!

Related articles:

A small function that inserts a string at a specified position.

PHP development skills (10)-implementation of Chinese character string truncation without garbled characters

Code explanation of string format calculation formula using eval in php

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.