How to customize and intercept Chinese strings in php

Source: Internet
Author: User
This topic describes in detail how to customize and intercept Chinese strings in php. The implementation method of the code is displayed to help beginners learn. Php custom truncation of Chinese Strings-utf8

The encoding range of the UTF-8 (UTF-8 uses 1-6 bytes to encode characters, actually only uses 1-4 bytes ):

1 byte: 00--7F2 byte: C080--DFBF3 characters: E08080--EFBFBF4 characters: F0808080--F7BFBFBF
$ Str = 'abcd I am China'; echo strlen ($ str ),'
'; Echo mstrlen ($ str ),'
'; Echo msubstr ($ str, 3, 9);/*** count the string length in utf8 */function mstrlen ($ str) {$ len = 0; $ I = 0; $ slen = strlen ($ str); while ($ I <$ slen) {$ o = ord ($ str [$ I]); if ($ o <127) {$ I ++;} elseif ($ o <224) {$ I + = 2;} else {$ I + = 3 ;} $ len ++;} return $ len;}/*** truncate the UTF-8 encoded string */function msubstr ($ str, $ start, $ length) {$ len = mstrlen ($ str); if ($ start <0) {$ start + = $ len; if ($ start <0) {$ start = 0 ;}} $ slen = strlen ($ str); $ index = 0; for ($ I = 0; $ I <$ start & $ I <$ slen; $ I ++) {$ o = ord ($ str [$ index]); if ($ o <127) {$ index ++;} elseif ($ o <224) {$ index + = 2;} else {$ index + = 3; }}$ length + = $ index; $ newStr = ''; for ($ I = $ index; $ I <$ length & $ I <$ slen; $ I ++) {$ o = ord ($ str [$ I]); if ($ o <127) {$ newStr. = $ str [$ I];} elseif ($ o <224) {$ newStr. = substr ($ str, $ I, 2); $ I + = 1; $ length ++;} else {$ newStr. = substr ($ str, $ I, 3); $ I + = 2; $ length + = 2;} return $ newStr ;}

The preceding figure shows how to customize and intercept Chinese strings in php. For more information, see other related articles in the first PHP community!

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.