以下两个方法的代码比较长,也是在网上搜到的,我把格式整理了一下,直接拷贝就可以用,非常方便,
主函数方法名:smarty_modifier_truncate_utf8和smarty_modifier_truncate_gbk
GBK编码下的截串动作
function gbk_strlen($string)
{
if(extension_loaded('mbstring')) {
mb_internal_encoding('GBK');
return mb_strlen($string);
}
else {
preg_match_all('/[\x81-\xfe]?./', $string, $match);
return count($match[0]);
}
}
function gbk_substr($string, $start, $length = null) {
if(extension_loaded('mbstring')) {
mb_internal_encoding('GBK');
if(is_null($length)) {
return mb_substr($string, $start);
}
else {
return mb_substr($string, $start, $length);
}
}
else {
preg_match_all('/[\x81-\xfe]?./', $string, $match);
if(is_null($length)) {
return implode('', array_slice($match[0], $start));
}
else {
return implode('', array_slice($match[0], $start, $length));
}
}
}
function smarty_modifier_truncate_gbk($string, $length = 80, $etc = '...', $break_words = false, $middle = false) {
if ($length == 0) return '';
if (gbk_strlen($string) > $length) {
$length -= gbk_strlen($etc);
if (!$break_words && !$middle) {
$string = preg_replace('/\s+?(\S+)?$/', '', gbk_substr($string, 0, $length+1));
}
if(!$middle) {
return gbk_substr($string, 0, $length).$etc;
} else {
return gbk_substr($string, 0, $length/2) . $etc . gbk_substr($string, -$length/2);
}
} else {
return $string;
}
}
//UTF-8编码下的方法
function smarty_modifier_truncate_utf8($string, $length, $etc = '...') {
$result = '';
$string = html_entity_decode(trim(strip_tags($string)), ENT_QUOTES, 'UTF-8');
$strlen = strlen($string);
for($i = 0; (($i < $strlen) && ($length > 0)); $i++)
{
if($number = strpos(str_pad(decbin(ord(substr($string, $i, 1))), 8, '0', STR_PAD_LEFT), '0'))
{
if($length < 1.0) {
break;
}
$result .= substr($string, $i, $number);
$length -= 1.0;
$i += $number - 1;
}
else {
$result .= substr($string, $i, 1);
$length -= 0.5;
}
}
$result = htmlspecialchars($result, ENT_QUOTES, 'UTF-8');
if($i < $strlen) {
$result .= $etc;
}
return $result;
}PHP下截取字符串的有效方法(mb_string替代方案)
转自:http://hi.baidu.com/wader2006/blog/item/298bce1b2b80a9fcae513365.html