<?php
/**
* @@Description 截取字符串
* @param String(字符串) $key
* @param Int(
字符串截取长度) $length
* @param String(后缀eg:...) $postfix
* @param Int(字符串开始位置) $start
* @param String(编码) $code
* @return String
*/
function strCut( $key, $length = 1, $postfix = "...", $start = 0, $code = 'UTF-8' ) {
if( 'UTF-8' == $code ) {
$pattern = "/[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]/";
preg_match_all( $pattern, $key, $result );
if( count( $result[0] ) - $start > $length ) {
return join( '', array_slice( $result[0], $start, $length ) ).$postfix;
}
return join( '', array_slice( $result[0], $start, $length ) );
}else{
$start = $start * 2;
$length = $length * 2;
$strlen = strlen( $key );
$tmpstr = '';
for ( $i = 0; $i < $strlen; $i++ ) {
if( $i >= $start && $i < ($start + $length) ) {
if( ord( substr( $key, $i, 1 ) ) > 129 ) {
$tmpstr.= substr( $key, $i, 2 );
}else{
$tmpstr.= substr( $key, $i, 1 );
}
}
if( ord( substr( $key, $i, 1 ) ) > 129 ) {
$i++;
}
}
if( strlen( $tmpstr ) < $strlen ) {
$tmpstr.= $postfix;
}
return $tmpstr;
}
}