PHP Intercept String If it is English directly with SUBSTR can, but for Chinese characters, with substring may lead to garbled, then how to solve it?
1, through the function mb_substr realization
Description: Mb_substr ($STR, $start, $length, $encoding); This function is available, but the php_mbstring.dll extension needs to be loaded.
Case:
<?php $str = ' This is a string cutting function '; echo "Mb_substr:". Mb_substr ($str, 0, 7, ' utf-8 ');?>
2, through the function mb_strcut realization
Description: Mb_strcut () and MB_SUBSTR () are similar in that they extract substrings from a string, but are executed in bytes instead of the number of characters. If the truncation position is in the middle of a multibyte character of two bytes, execution begins at the first byte of the character. This is also the difference from the substr () function, which simply truncates the string between bytes, which results in a malformed byte sequence.
3, through the written function (supports UTF-8 and GB2312)
Case:
<?php /* utf-8, gb2312 both support the Chinese character intercept function cut_str (string, intercept length, start length, encoding); encoding defaults to utf-8 start length defaults to 0 */ function cut_str ($string, $sublen, $start = 0, $code = ' UTF-8 ') { $string = str_ Replace (Array (' & ', ' ', ' < ', ' > '), array (' & ', ' "', ' < ', ' > '), $string) 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 +) { &nbsP; if ($i >= $start && $i < ($start + $sublen)) { if (Ord (substr ($string, $i, 1) >0xa0) { $tmpstr. = substr ($string, $i, 2); } else { $tmpstr. = substr ($string, $i, 1); } } if (Ord (substr ($string, $i, 1) >0xa0) $i ++; } if (strlen ($ TMPSTR) < $strlen ) $tmpstr .= "..."; return $tmpstr; } } $str = "This is a string cutting function"; echo cut_str ($str, 8, 0, ' gb2312 '); ?>
PHP Chinese string truncation garbled