How to intercept Chinese strings in php? As we all know, the native function substr of php does not support intercepting Chinese strings. The following code provides a variety of methods to intercept php Chinese strings. 1. intercept the GB2312 Chinese string & lt ;? Php & lt ;? Php // Intercept a Chinese string functionmysubstr ($ str, $ sta php: how to intercept a Chinese string?
As we all know, the native function substr of php does not support intercepting Chinese strings. The following code provides a variety of methods to intercept php Chinese strings.
1. truncate the GB2312 Chinese string
0xa0) {$ tmpstr. = substr ($ str, $ I, 2); $ I ++;} else $ tmpstr. = substr ($ str, $ I, 1);} return $ tmpstr ;}?>
2. truncate UTF-8 encoded multi-byte strings
3. UTF-8, GB2312 support Chinese character truncation function
$ Sublen) return join ('', array_slice ($ t_string [0], $ start, $ sublen )). "... "; return join ('', array_slice ($ t_string [0], $ start, $ sublen);} else {$ start = $ start * 2; $ sublen = $ sublen * 2; $ strlen = strlen ($ string); $ tmpstr = ''; for ($ I = 0; $ I <$ strlen; $ I ++) {if ($ I >=$ start & $ I <($ start + $ sublen) {if (ord (substr ($ string, $ I, 1)> 129) {$ tmpstr. = substr ($ string, $ I, 2);} else {$ tmpstr. = substr ($ str Ing, $ I, 1) ;}} if (ord (substr ($ string, $ I, 1)> 129) $ I ++ ;} if (strlen ($ tmpstr) <$ strlen) $ tmpstr. = "... "; return $ tmpstr ;}}$ str =" string to be intercepted by abcd "; echo cut_str ($ str, 8, 0, 'gb2312');?>
4. BugFree character truncation function
<? Php/*** @ package BugFree * @ version $ Id: FunctionsMain. inc. php, v 1.32 11:38:37 wwccss Exp $ *** Return part of a string (Enhance the function substr () ** @ author Chunsheng Wang
* @ Param string $ String the string to cut. * @ param int $ Length the length of returned string. * @ param booble $ Append whether append "... ": false | true * @ return string the cutted string. */function sysSubStr ($ String, $ Length, $ Append = false) {if (strlen ($ String) <=$ Length) {return $ String ;} else {$ I = 0; while ($ I <$ Length) {$ StringTMP = substr ($ String, $ I, 1); if (ord ($ StringTMP)> = 224 ){ $ StringTMP = substr ($ String, $ I, 3); $ I = $ I + 3;} elseif (ord ($ StringTMP)> = 192) {$ StringTMP = substr ($ String, $ I, 2); $ I = $ I + 2;} else {$ I = $ I + 1 ;} $ StringLast [] = $ StringTMP;} $ StringLast = implode ("", $ StringLast); if ($ Append) {$ StringLast. = "... ";}return $ StringLast ;}$ String =" 17test.info is at the forefront of China's automated testing "; $ Length =" 18 "; $ Append = false; echo sysSubStr ($ String, $ Length, $ Append);?>