下一篇 ? ? 上一篇

smart下截取汉字

作者: ???时间:2008-04-07??? 来源:??? 点击:41993 ???本文共1篇文章 字体:[ ]

utf-8编码,一个汉字占三个字节:

function smarty_modifier_cntruncate($string, $strlen = 20, $etc = '...', $keep_first_style = false)
{
??? $strlen = $strlen*3;
??? $string = trim($string);
??? if ( strlen($string) <= $strlen )??? {
??????? return $string;
??? }
??? $str = strip_tags($string);
??? $j = 0;

??? for($i=0;$i<$strlen;$i++) {
??????? if(ord(substr($str,$i,1))>0xa0){ $i+=2; $j+=3;}
??????? else {$j++;}
??? } 本文来自 www.444p.com

??? $rstr=substr($str,0,$j);
??? if (strlen($str)>$strlen ) {$rstr .= $etc;}

www.444p.com版权所有

??? if ( $keep_first_style == true && ereg('^<(.*)>$',$string) )??? {
??????? if ( strlen($str) <= $strlen )??? {
??????????? return $string;
??????? }
??????? $start_pos = strpos($string,substr($str,0,4));
??????? $end_pos = strpos($string,substr($str,-4));
??????? $end_pos = $end_pos+4;
??????? $rstr = substr($string,0,$start_pos) . $rstr . substr($string,$end_pos,strlen($string));
??? }

??? return $rstr;

php学习之家

} php学习之家

gb2312编码,一个汉字占两字节:

www.444p.com php学习之家


function smarty_modifier_cntruncate($string, $strlen = 20, $etc = '...', $keep_first_style = false)
{
??? $strlen = $strlen*2;
??? $string = trim($string);
??? if ( strlen($string) <= $strlen ) {
??? return $string;
}
$str = strip_tags($string);
$j = 0;
for($i=0;$i<$strlen;$i++) {
??? if(ord(substr($str,$i,1))>0xa0) $j++;
}
if($j%2!=0) $strlen++;
$rstr=substr($str,0,$strlen);
if (strlen($str)>$strlen) {$rstr .= $etc;} www.444p.com

if ( $keep_first_style == true && ereg('^<(.*)>$',$string) ) {
??? if ( strlen($str) <= $strlen ) {
??????? return $string;
??? }
??? $start_pos = strpos($string,substr($str,0,4));
??? $end_pos = strpos($string,substr($str,-4));
??? $end_pos = $end_pos+4;
??? $rstr = substr($string,0,$start_pos) . $rstr . substr($string,$end_pos,strlen($string));
}
return $rstr;
}

www.444p.com

责任编辑:semirock

最新评论(共有 1 条评论)更多评论...

  • 游客: 游客的评论 (2009-04-19 19:14 pm)
    OK。。。
    嘻嘻~~~
    谢谢了。
发表评论
密码: (游客不需要密码)
记住我【Alt+S 或 Ctrl+Enter 快速提交】

搜索工具