CopyCode The Code is as follows: <? PHP
/* Chinese characters truncation of UTF-8 Program */
$ STR = "123 this is a test string ";
$ Str1 = "()()";
Echo subutf8str ($ STR, 0, 3). "<br> ";
Echo subutf8str ($ STR, 0,4). "<br> ";
Echo subutf8str ($ str1, 0, 4). "<br> ";
Echo subutf8str ($ str1, 0, 10). "<br> ";
Function subutf8str ($ STR, $ start = 0, $ length = 80 ){
$ Cur_len = 0; // String Length understood by a person
$ All_len = strlen ($ Str); // machine understanding String Length
If ($ length> $ all_len)
{
Return $ STR;
}
For ($ I = 0; $ I <$ all_len ;)
{
If ($ cur_len = $ start)
{
Break;
}
If (ord ($ STR [$ I])> 127)
{
$ I + = 3;
} Else {
$ I + = 1;
}
$ Cur_len ++;
}
$ Start_pos = $ I;
$ Temp_pos = $ cur_len;
For (; $ cur_len-$ temp_pos <$ length ;)
{
If ($ I >=$ all_len)
Break;
If (ord ($ STR [$ I])> 127)
{
$ I + = 3;
} Else {
$ I + = 1;
}
$ Cur_len ++;
}
$ End_pos = $ I;
Return substr ($ STR, $ start_pos, $ end_pos );
}
?>
In fact, PHP native has a multi-charset character truncation scheme, the amount, so it looks like this... pretty ..
In The multibyte string functions function family,
String mb_substr (string $ STR, int $ start [, int $ length [, string $ encoding]) is used to intercept strings.
Int mb_strlen (string $ STR [, string $ encoding]) returns the string length.
....
For more information, see the PHP manual.