首页 > 资讯列表 > 编程/数据库 >> PHP

php中文裁减字符串函数

PHP 2014-12-19 07:48:03 转载来源: 网络整理/侵权必删

本文为大家提供的是一个php中文裁减字符串函数,感兴趣的同学参考下. define(CHARSET, 'UTF-8'); // 系统默认编码 /** * 根据中文裁减字符串 * @param $string - 字符串 * @param $length - 长度 * @param $doc - 缩略后缀 * @return 返回带省略号被裁减好的字符串 */ function cutstr( $string, $length, $dot = '

本文为大家提供的是一个php中文裁减字符串函数,感兴趣的同学参考下.


define(CHARSET, 'UTF-8'); // 系统默认编码

/**
* 根据中文裁减字符串
* @param $string - 字符串
* @param $length - 长度
* @param $doc - 缩略后缀
* @return 返回带省略号被裁减好的字符串
*/
function cutstr( $string, $length, $dot = '...' ) {
if ( strlen( $string ) <= $length ) {
return $string;
}
$pre = chr( 1 );
$end = chr( 1 );
$string = str_replace( array( '&', '"', '<', '>' ), array( $pre . '&' . $end, $pre . '"' . $end, $pre . '<' . $end, $pre . '>' . $end ), $string );
$strcut = '';
if ( strtolower( CHARSET ) == 'utf-8' ) {
$n = $tn = $noc = 0;
while ( $n < strlen( $string ) ) {
$t = ord( $string[$n] );
if ( $t == 9 || $t == 10 || (32 <= $t && $t <= 126) ) {
$tn = 1;
$n++;
$noc++;
} elseif ( 194 <= $t && $t <= 223 ) {
$tn = 2;
$n += 2;
$noc += 2;
} elseif ( 224 <= $t && $t <= 239 ) {
$tn = 3;
$n += 3;
$noc += 2;
} elseif ( 240 <= $t && $t <= 247 ) {
$tn = 4;
$n += 4;
$noc += 2;
} elseif ( 248 <= $t && $t <= 251 ) {
$tn = 5;
$n += 5;
$noc += 2;
} elseif ( $t == 252 || $t == 253 ) {
$tn = 6;
$n += 6;
$noc += 2;
} else {
$n++;
}
if ( $noc >= $length ) {
break;
}
}
if ( $noc > $length ) {
$n -= $tn;
}
$strcut = substr( $string, 0, $n );
} else {
for ( $i = 0; $i < $length; $i++ ) {
$strcut .= ord( $string[$i] ) > 127 ? $string[$i] . $string[++$i] : $string[$i];
}
}
$strcut = str_replace( array( $pre . '&' . $end, $pre . '"' . $end, $pre . '<' . $end, $pre . '>' . $end ), array( '&', '"', '<', '>' ), $strcut );
$pos = strrpos( $strcut, chr( 1 ) );
if ( $pos !== false ) {
$strcut = substr( $strcut, 0, $pos );
}
return $strcut . $dot;
}

标签: php 中文 裁减 字符串 函数


声明:本文内容来源自网络,文字、图片等素材版权属于原作者,平台转载素材出于传递更多信息,文章内容仅供参考与学习,切勿作为商业目的使用。如果侵害了您的合法权益,请您及时与我们联系,我们会在第一时间进行处理!我们尊重版权,也致力于保护版权,站搜网感谢您的分享!

站长搜索

http://www.adminso.com

Copyright @ 2007~2024 All Rights Reserved.

Powered By 站长搜索

打开手机扫描上面的二维码打开手机版


使用手机软件扫描微信二维码

关注我们可获取更多热点资讯

站长搜索目录系统技术支持