Php Tutorial support gb2312, uft-8 Chinese and English character truncation function
<? Php
// Intercept the gb2312 Chinese string
Function mysubstr ($ str, $ start, $ len ){
$ Tmps tutorial tr = "";
$ Strlen = $ start + $ len;
For ($ I = 0; $ I <$ strlen; $ I ++ ){
If (ord (substr ($ str, $ I, 1)> 0xa0 ){
$ Tmpstr. = substr ($ str, $ I, 2 );
$ I ++;
} Else
$ Tmpstr. = substr ($ str, $ I, 1 );
}
Return $ tmpstr;
}
?>
<? Php
// Truncate the utf8 string
Function utf8substr ($ str, $ from, $ len)
{
Return preg_replace ('# ^ (? : [X00-x7f] | [xc0-xff] [x80-xbf] +) {0, '. $ from .'}'.
'((? : [X00-x7f] | [xc0-xff] [x80-xbf] +) {0, '. $ len.'}). * # s ',
'$ 1', $ str );
}
?>
Integrate the above two examples
<? Php
/*
Chinese character truncation functions supported by UTF-8 and gb2312
Cut_str (string, truncation length, start length, encoding );
The default encoding format is UTF-8.
The default start length is 0.
*/
Function cut_str ($ string, $ sublen, $ start = 0, $ code = 'utf-8 ')
{
If ($ code = 'utf-8 ')
{
$ Pa = "/[x01-x7f] | [xc2-xdf] [x80-xbf] | xe0 [xa0-xbf] [x80-xbf] | [xe1-xef] [x80-xbf] [x80-xbf] | xf0 [x90-xbf] [x80-xbf]] [x80-xbf] | [xf1-xf7] [x80-xbf] [x80-xbf] [x80-xbf]/";
Preg_match_all ($ pa, $ string, $ t_string );
If (count ($ t_string [0])-$ start> $ 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 ($ string, $ I, 1 );
}
}
If (ord (substr ($ string, $ I, 1)> 129) $ I ++;
}
If (strlen ($ tmpstr) <$ strlen) $ tmpstr. = "...";
Return $ tmpstr;
}
}
$ Str = "the string to be intercepted by abcd ";
Echo cut_str ($ str, 8, 0, 'gb2312 ');
?>