Smarty truncateJ 按文字占据视觉空间长度截取字符串

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jiongxian1/article/details/89444973
<?php
/*
 * 按文字占据视觉空间长度截取字符串
 * 2个英文或2个数字占一个中文的视觉显示空间长度
*/
function smarty_modifier_truncateJ($string, $length = 30, $etc = '...')
{
    if ($length == 0) {
        return '';
    }
	$len = 0;
	$ci = 0;
	//原字符串超长时,截取后的字符串要减去省略号的长度
	$length -= mb_strlen($etc);
	//2个英文或2个数字占一个中文的视觉显示空间长度
	$len = $length*2;
	for($i=0; $i<mb_strlen($string);$i++){
		$str = mb_substr($string,$i,1);
		if(preg_match('/[^\x00-\x7F]/i', $str)){
			//中文,+2
			$ci += 2;
		} else{
			//非中文,+1
			$ci += 1;
		}
		//超长,跳出循环
		if($ci > $length*2){
			break;
		} else{
			$len = $i;
		}
	}
	//$len+1为满足视觉显示长度后的最终字符串长度
	return mb_substr($string, 0, $len+1).$etc;
	/* if(preg_match('/[^\x00-\x7F]/i', mb_substr($string, $len, 1))){
		//最后一个字符为中文
		return mb_substr($string, 0, $len+1).$etc;
	} else{
		return mb_substr($string, 0, $len).$etc;
	} */
}

不知道通用不,有问题可以联系我,尽量修改,不喜请勿喷

猜你喜欢

转载自blog.csdn.net/jiongxian1/article/details/89444973