Hàm cắt chuỗi, tiêu đề Unicode trong PHP

Đây là hàm cắt chuỗi unicode được sử dụng khá nhiều trên các website.

function cstr($text$start=0$limit=12)
    {
        if (
function_exists('mb_substr')) {
            
$more = (mb_strlen($text) > $limit) ? TRUE FALSE;
            
$text mb_substr($text0$limit'UTF-8');
            return array(
$text$more);
        } elseif (
function_exists('iconv_substr')) {
            
$more = (iconv_strlen($text) > $limit) ? TRUE FALSE;
            
$text iconv_substr($text0$limit'UTF-8');
            return array(
$text$more);
        } else {
              
preg_match_all("/[\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]/",  $text$ar);
            if(
func_num_args() >= 3) {
                if (
count($ar[0])>$limit) {
                    
$more TRUE;
                    
$text join("",array_slice($ar[0],0,$limit))."...";
                }
                
$more TRUE;
                
$text join("",array_slice($ar[0],0,$limit));
            } else {
                
$more FALSE;
                
$text =  join("",array_slice($ar[0],0));
            }
            return array(
$text$more);
        }
}
function 
sub_str($text$limit=25)
{
    
$val cstr($text0$limit);
    return 
$val[1] ? $val[0]."..." $val[0];
 

Cách sử dụng:
PHP Code:
$str "Hỗ trợ lập trình";

echo 
sub_str($str5);  


Và một số hàm cắt tiêu đề bài viết có thể nói là tương đối ổn.

function cut_string($str,$len,$more){ //Hàm cắt đoạn văn
    if ($str=="" || $str==NULL) return $str;
    if (is_array($str)) return $str;
    $str = trim($str);
    if (strlen($str) <= $len) return $str;
    $str = substr($str,0,$len);
    if ($str != "") {
    if (!substr_count($str," ")) {
    if ($more) $str .= " ...";
    return $str;
    }
    while(strlen($str) && ($str[strlen($str)-1] != " ")) {
    $str = substr($str,0,-1);
    }
    $str = substr($str,0,-1);
    if ($more) $str .= " ...";
    }
    return $str;
}

function cut_title($text, $len) { //Hàm cắt tiêu đề Unicode
    mb_internal_encoding('UTF-8');
    if( (mb_strlen($text, 'UTF-8') > $len) ) {
        $text = mb_substr($text, 0, $len, 'UTF-8');
        $text = mb_substr($text, 0, mb_strrpos($text," ", 'UTF-8'), 'UTF-8')."...";
    }
    return $text;
}

Không có nhận xét nào:

Đăng nhận xét