不言不语

您现在的位置是: 首页 >  PHP

PHP

PHP自定义截取字符串函数

2022-06-01PHP
PHP自​定义截取字符串函数,第一个参数$Str为截取字符串,第二个参数$Length为需要截取的长度,第三个参数为可选,代码如下:


/*
 *
 *	PHP自定义截取字符串函数
 *	
 *	$Str 截取字符串 
 *  $Length 截取的长度
 *  $more 可选 超出部分隐藏替换成'...'
 *  http://www.yanyublog.cn
 *
 */
function cut($Str, $Length,$more=true){
    global $s;
    $i = 0;
    $l = 0;
    $ll = strlen($Str);
    $s = $Str;
    $f = true;
	
    while ($i <= $ll) {
        if(ord($Str{$i}) < 0x80){
            $l++; $i++;
        }else if(ord($Str{$i}) < 0xe0){
            $l++; $i += 2;
        }else if(ord($Str{$i}) < 0xf0){
            $l += 2; $i += 3;
        }else if(ord($Str{$i}) < 0xf8){
            $l += 1; $i += 4;
        }else if(ord($Str{$i}) < 0xfc){
            $l += 1; $i += 5;
        }else if(ord($Str{$i}) < 0xfe){
            $l += 1; $i += 6;
        }
		
        if(($l >= $Length - 1) && $f){
            $s = substr($Str, 0, $i);
            $f = false;
        }
		
        if(($l > $Length) && ($i < $ll) && $more){
			//如果进行了截取,字符串末尾加省略符号“...”
            $s = $s . '...'; break; 
        }
    }
	
    return $s;
}


文章评论