Php implements Chinese character string truncation without garbled characters

Source: Internet
Author: User
The key point is to determine whether the string to be intercepted is a Chinese or English character. it can be determined by ord (substr ($ str, $ start, 1) & gt; 0xa0, if the value is greater than, it is in Chinese; otherwise, it is in English. The implementation code is as follows:

What you need to know on the homepage:
1. Chinese characters occupy 2 bytes in gbk encoding and 3 bytes in UTF-8 encoding.

2. the ord () function returns the ASCII value of the first character of the string.

3. the ASCII value of Chinese characters is greater than 0xa0.

The key point is to determine whether the string to be intercepted is a Chinese character or an English character. use ord (substr ($ str, $ start, 1)> 0xa0 to determine whether it is a Chinese character if it is greater than 0, otherwise, it is in English. The implementation code is as follows:

12345678910111213141516171819202122232425262728293031323334353637383940414243444546 0xa0) {$ pos + = $ bite; // if it is a Chinese character, the location is added with the noon character length;} else {$ pos + = 1 ;}} if ($ length = "") {returnsubstr ($ str, $ pos); // if $ length is empty, from the beginning to the last one} else {if ($ length <0) {$ length = 0 ;}$ string = ""; for ($ I = 1; $ I <= $ length; $ I ++) {if (ord (substr ($ str, $ pos, 1)> 0xa0) {// if it is a noon character, $ string. = substr ($ str, $ pos, $ bite); // capture $ pos + = $ bite according to the length of the noon character;} else {$ string. = substr ($ str, $ pos, 1); $ pos + = 1 ;}}return $ string ;}$ str = "a This is a Chinese character"; echomy _ Substr ($ str, 0); // output from the first to the last one. Echo"
"; Echomy_substr ($ str, 0, 1); // output a; echo"
"; Echomy_substr ($ str, 1, 2); // output this; echo"
"; // Echo my_substr ($ str, 3); // if it is UTF-8 encoded, the last parameter is changed to 3;?>

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.