保定网站建设,网站推广,网站优化服务,保定专业的PHP网站制作机构!

PHP截取任意UTF8编码字符函数(截取中文字符串)

发表于:2009年01月05日 17时  作者:dx_andy

PHP 函数 utf8_strcut 截取中文字符串

/**
* 截取utf-8字符串
* @since 2008.12.23
* @param string $str 被截取的字符串
* @param integer $start 起始位置
* @param integer $length 截取长度(每个汉字为3字节)
*/
function utf8_strcut($str, $start, $length=null) {
preg_match_all(‘/./us’, $str, $match);
$chars = is_null($length)? array_slice($match[0], $start ) : array_slice($match[0], $start, $length);
return implode(”, $chars);
}

函数取自Wordpress。能够完美的截取UTF8下的任意字符,包括:中文,韩文,日文。

PHP截取中文字符串函数utf8_substr

发表于:2008年07月10日 17时  作者:dx_andy

PHP截取中文字符串utf8_substr函数代码

// 中文字符串截取
function utf8_substr($str, $start, $length) {
$pa=”/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|”;
$pa.=”\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/”;
preg_match_all($pa, $str, $t_string);
if(count($t_string[0]) - $start > $length) {
return join(”, array_slice($t_string[0], $start, $length)) . “..”;
} else {
return join(”, array_slice($t_string[0], $start, $length));
}
}