+ -
当前位置:首页 → 问答吧 → 扩展smarty 截取方法truncate支持中文

扩展smarty 截取方法truncate支持中文

时间:2008-06-03

来源:互联网

/Smarty/plugins/modifier.truncate_cn.php
复制内容到剪贴板
代码:
<?
function smarty_modifier_truncate_cn($string, $length = 80, $code = '', $etc = '')
{
if ($length == 0)
return '';
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]/";
}
else{
$pa = "/[\x01-\x7f]|[\xa1-\xff][\xa1-\xff]/";
}
preg_match_all($pa, $string, $t_string);
if(count($t_string[0]) > $length)
return join('', array_slice($t_string[0], 0, $length)).$etc;
return join('', array_slice($t_string[0], 0, $length));
}
?>

作者: wz_910   发布时间: 2008-06-03

支持,我早就知道了其实!

作者: kaixin99   发布时间: 2008-06-03

谁来解释一下

作者: linvo   发布时间: 2008-06-04

看到正则 我就晕

作者: phpcaicai   发布时间: 2008-06-04

学习下!

作者: 从头再来   发布时间: 2008-06-18

贴上一段我同事两年前写的函数。
复制PHP内容到剪贴板
PHP代码:
function smarty_modifier_truncateex($string, $length = 80, $encoded = "utf-8", $etc = '...',
                                  $break_words = false, $middle = false)
{
    if ($length == 0)
        return '';
    if (mb_strlen($string, $encoded) > $length) {
        $length -= mb_strlen($etc, $encoded);
        if (!$break_words && !$middle) {
            $string = preg_replace('/\s+?(\S+)?$/', '', mb_substr($string, 0, $length+1, $encoded));
        }
        if(!$middle) {
            return mb_substr($string, 0, $length, $encoded).$etc;
        } else {
            return mb_substr($string, 0, $length/2, $encoded) . $etc . mb_substr($string, -$length/2, $encoded);
        }
    } else {
        return $string;
    }
}

作者: 欧阳   发布时间: 2008-07-22

热门下载

更多