thinkphp3.2.3在框架截取文字

时间:2022-11-04 05:13:43

Common/Common/function.php加入以下代码

/**
*
* 字符截取
* @param string $string
* @param int $start
* @param int $length
* @param string $charset
* @param string $dot
*
* @return string
*/
function str_cut(&$string, $start, $length, $charset = "utf-8", $dot = '...') {
if(function_exists('mb_substr')) {
if(mb_strlen($string, $charset) > $length) {
return mb_substr ($string, $start, $length, $charset) . $dot;
}
return mb_substr ($string, $start, $length, $charset); }else if(function_exists('iconv_substr')) {
if(iconv_strlen($string, $charset) > $length) {
return iconv_substr($string, $start, $length, $charset) . $dot;
}
return iconv_substr($string, $start, $length, $charset);
} $charset = strtolower($charset);
switch ($charset) {
case "utf-8" :
preg_match_all("/[\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]/", $string, $ar);
if(func_num_args() >= 3) {
if (count($ar[0]) > $length) {
return join("", array_slice($ar[0], $start, $length)) . $dot;
}
return join("", array_slice($ar[0], $start, $length));
} else {
return join("", array_slice($ar[0], $start));
}
break;
default:
$start = $start * 2;
$length = $length * 2;
$strlen = strlen($string);
for ( $i = 0; $i < $strlen; $i++ ) {
if ( $i >= $start && $i < ( $start + $length ) ) {
if ( ord(substr($string, $i, 1)) > 129 ) $tmpstr .= substr($string, $i, 2);
else $tmpstr .= substr($string, $i, 1);
}
if ( ord(substr($string, $i, 1)) > 129 ) $i++;
}
if ( strlen($tmpstr) < $strlen ) $tmpstr .= $dot; return $tmpstr;
}
}

view下

<volist name='' item ='v'>
{$v.content|msubstr=5,5,'utf-8',false}
</volist>
/**
msubstr($str, $start=0, $length, $charset=”utf-8″, $suffix=true)
$str:要截取的字符串
$start=0:开始位置,默认从0开始
$length:截取长度
$charset=”utf-8″:字符编码,默认UTF-8
$suffix=true:是否在截取后的字符后面显示省略号,默认true显示,false为不显示
**/