WordPress UTF8 中文截取

UTF8 中文截取
其中对字符串预先 __() 处理,可以从 qtranslate 中取出当前语言部分然后进行截取。

        function the_excerpt_max_charlength($charlength) {
            $excerpt = get_the_excerpt();
            $charlength++;

            if (mb_strlen($excerpt) > $charlength) {
                $subex = mb_substr($excerpt, 0, $charlength - 5);
                $exwords = explode(' ', $subex);
                $excut = - ( mb_strlen($exwords[count($exwords) - 1]) );
                if ($excut < 0) {
                    echo mb_substr($subex, 0, $excut);
                } else {
                    echo $subex;
                }
                echo '...';
            } else {
                echo $excerpt;
            }
        }
function utf8Substr($str, $from, $len)
{
    if ($len == 0){
		return __($str);
	}else{

    return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
                       '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
                       '$1',__($str));
	}
}
//use
utf8Substr($recent["post_title"],0,14);
function utf8_trim($str) {

	$len = strlen($str);

	for ($i=strlen($str)-1; $i>=0; $i-=1){
		$hex .= ' '.ord($str[$i]);
		$ch = ord($str[$i]);
        if (($ch & 128)==0) return(substr($str,0,$i));
		if (($ch & 192)==192) return(substr($str,0,$i));
	}
	return($str.$hex);
}

function mul_excerpt ($excerpt) {
     $myexcerpt = substr($excerpt,0,255);
     return utf8_trim($myexcerpt) . ' ... ';
}

add_filter('the_excerpt', 'mul_excerpt');

放在function.php 文件里,对 the_excerpt 过滤处理, 长度为 255,也可以换成你想要的长度。

Comments are closed.