In PHP, the character intercept function substr can only intercept the whole English language will not appear garbled if there is Chinese is certainly not intercepted, the following small series to introduce two compatible various types of GBK,UTF-8 encoded string intercept function
Example 1
function Csubstrpro ($str, $start, $length, $charset = "Utf-8", $suffix = False) { if (function_exists ("Mb_substr")) C1/>return mb_substr ($str, $start, $length, $charset); $re [' utf-8 '] = "/[x01-x7f]| [XC2-XDF] [x80-xbf]| [Xe0-xef] [X80-XBF] {2}| [Xf0-xff] [X80-XBF] {3}/"; $re [' gb2312 '] = "/[x01-x7f]| [Xb0-xf7] [xa0-xfe]/]; $re [' gbk '] = "/[x01-x7f]| [X81-xfe] [x40-xfe]/]; $re [' big5 '] = "/[x01-x7f]| [X81-xfe] ([X40-x7e]|xa1-xfe]) /"; Preg_match_all ($re [$charset], $STR, $match); $slice = Join ("", Array_slice ($match [0], $start, $length)); if ($suffix) return $slice. "…"; return $slice;}
Example 2
function Substring_utf8 ($str, $start, $lenth) {$len = strlen ($STR); $r = Array (); $n = 0; $m = 0; for ($i = 0; $i < $len; $i + +) {$x = substr ($str, $i, 1); $a = Base_convert (ord ($x), 10, 2); $a = substr (' 00000000 '. $a,-8); if ($n < $start) {if (substr ($a, 0, 1) = = 0) {}elseif (substr ($a, 0, 3) = = 110) { $i + = 1; }elseif (substr ($a, 0, 4) = = 1110) {$i + = 2; } $n + +; }else{if (substr ($a, 0, 1) = = 0) {$r [] = substr ($str, $i, 1); }elseif (substr ($a, 0, 3) = =) {$r [] = substr ($str, $i, 2); $i + = 1; }elseif (substr ($a, 0, 4) = = 1110) {$r [] = substr ($str, $i, 3); $i + = 2; }else{$r [] = "; } if (+ + $m >= $lenth) {break; }}} return $r; }//End Substring_utf8;} End String
#由于此函数返回的是一个数组, so match the join function to display the string: Example 2
#join (", Substring_utf8 ($str, $start, $lenth));
#在页面显示的时候还可以在此语句后面连一个 "..."
The above is the PHP character interception function, compatible with various types of gbk,utf-8 encoded content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!