The length of php strings varies according to the encoding. Is the Chinese character string of the UTF-8 three bytes? Php coding UTF-8echostrlen (test text a test text); echo-; echomb_strlen (test text a test text, UTF-8 );? Output: The Chinese string of the 25-9 GB UTF-8 is three bytes
// Coding UTF-8
Echo strlen ('test text a test text ');
Echo '-';
Echo mb_strlen ('test text a test text', 'utf-8 ');
?>
Output: 25-9
The Chinese string of GB2312 is two bytes.
// Code GB2312
Echo strlen ('test text a test text ');
Echo '-';
Echo mb_strlen ('test text a test text', 'gb2312 ');
?>
Output: 17-9
In Mysql databases (versions later than Mysql 5.1), if the field type is varchar (10), you can insert 10 characters (not Bytes );
Therefore, the length of a string must be determined by document encoding.
Character string truncation in a simple UTF-8 (by number of characters)
/*
* UTF-8 string truncation
* $ Str string to be intercepted
* $ Start: the starting position of the truncation.
* $ Length: truncation length
*/
Function cutStr ($ str, $ start, $ length ){
$ Restr = '';
$ J = 0;
$ End = $ length + $ start-1;
$ Plen = strlen ($ str );
For ($ I = 0; $ I <$ plen; $ I ++ ){
$ Restr. = ord ($ str [$ I])> 127? $ Str [$ I]. $ str [++ $ I]. $ str [++ $ I]: $ str [$ I];
$ J ++;
If ($ j <$ start) {$ restr = '';}
If ($ j >=$ end) {break ;}
}
$ Restr. = '';
Return $ restr;
}
$ Str = 'xinnet, September 11, September 24 (G20) leaders will hold the third financial summit in Pittsburgh, USA Today. ';
Echo $ str;
Echo'
';
Echo utf8_substr ($ str, 0, 25 );
Echo'
';
?>
Why? Php // coding UTF-8 echo strlen ('test text a test text'); echo '-'; echo mb_strlen ('test text a test text ', 'utf-8 ');? Output: 25-9 GB...