Implement phpUTF8 Chinese character string truncation by yourself

Source: Internet
Author: User
Self-implemented phpUTF8 Chinese string truncation header ("Content-type: text/html; charset = utf-8"); functionmy_substr ($ str, $ begin, $ length) {$ I = $ begin; $ r implements php UTF8 Chinese string truncation by itself
Header ("Content-type: text/html; charset = utf-8"); function my_substr ($ str, $ begin, $ length) {$ I = $ begin; $ result = ""; while ($ length> 0) {if ([color = red] ord ($ str [$ I])> 127 [/color]) {$ result. = substr ($ str, $ I, 3); $ I = $ I + 3;} else {$ result. = substr ($ str, $ I, 1); $ I ++;} $ length --;} return $ result;} $ chinese = "chinese people"; echo"
". My_substr ($ chinese, 0, 3 );



The output result is: China

Note:
Ord is the assic value for the character.
Chr is a character for assic.

Why is it determined that assic is greater than 127.

Here is the ASSIC code table
Http://www.asciitable.com/

In the computer, only ASSIC encoding is used to indicate characters. An ASSIC character is represented by a BYTE. Therefore, ASSIC has a maximum of 256 combinations. It is sufficient for English, but not for Chinese, Japanese, Korean, and other Asian languages.
Therefore, you can only use multiple bytes to represent a Chinese character. for example, GB2312 represents a Chinese character in two bytes. In windows, create a TXT file in the notebook and save it as ASSIC. if you are using a simplified Chinese operating system, the Chinese text in the TXT file is saved as GB2312. The program $ result. = substr ($ str, $ I, 3) in the above string is changed to 3. do not forget to modify the header. And whether GB2312 or UTF8 they said A-Z and other ASSIC 128 before is the same, is a BTYE representation, is variable length encoding. So we can use ASSIC to determine whether they are Chinese or not.

The write may be messy. Exercise caution when necessary.

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.