There are a lot of PHP beginners to intercept characters will use SUBSTR () function or mb_substr () function to intercept, the first Chinese must be garbled, the second performance is not good, the following I summed up a few custom Chinese text string interception without garbled instances.
Example 1
The code is as follows |
Copy Code |
function Msubstr ($str, $start =0, $length, $charset = "Utf-8", $suffix =true) { if (function_exists ("Mb_substr")) Return Mb_substr ($str, $start, $length, $charset); ElseIf (function_exists (' iconv_substr ')) { Return Iconv_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
The code is as follows |
Copy Code |
$start: Specifies the position at which to start intercepting the string, $length specifies the length of the Intercept character function Substr2 ($string, $start, $length) { $len = strlen ($string); if ($len > $length) { $str = "; $len 1 = $start + $length; The location where the original string was intercepted for ($i = $start; $i < $len 1; $i + +) { if (Ord (substr ($string, $i, 2)) > 0xa0)//in ASCII, 0xa0 denotes the beginning of the kanji { $str. =substr ($string, $i, 2); $i + +; } Else { $str. =substr ($string, $i, 1); } } return $str. ' ... '; } Else { return $string; } } ?> |
Add a simple, thinking the same (2010-5-31)
The code is as follows |
Copy Code |
function Chinesesubstr ($str, $start, $len) { $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; } $str = "Waiting for your Wait wait you back"; Echo chinesesubstr ($str, 0, 19) ?> |
http://www.bkjia.com/PHPjc/632772.html www.bkjia.com true http://www.bkjia.com/PHPjc/632772.html techarticle There are a lot of PHP beginners intercept characters will use SUBSTR () function or mb_substr () function to intercept, the first Chinese must be garbled, the second performance is not good, below I summed up a few custom ...