Code 1 Mã: function shortDesc($str, $len, $charset='UTF-8'){ $str = html_entity_decode($str, ENT_QUOTES, $charset); if(mb_strlen($str, $charset)> $len){ $arr = explode(' ', $str); $str = mb_substr($str, 0, $len, $charset); $arrRes = explode(' ', $str); $last = $arr[count($arrRes)-1]; unset($arr); if(strcasecmp($arrRes[count($arrRes)-1], $last)) { unset($arrRes[count($arrRes)-1]); } return implode(' ', $arrRes)."..."; } return $str; } //Goi ham $str = "Hàm cắt chuỗi Unicode với php"; echo shortDesc($str, 20); Code 2: Mã: function cstr($text, $start=0, $limit=12) { if (function_exists('mb_substr')){ $more = (mb_strlen($text) > $limit) ? TRUE : FALSE; $text = mb_substr($text, 0, $limit, 'UTF-8'); return array($text, $more); }else if(function_exists('iconv_substr')){ $more = (iconv_strlen($text) > $limit) ? TRUE : FALSE; $text = iconv_substr($text, 0, $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 cut_title($text, $limit=25) { $val = cstr($text, 0, $limit); return $val[1] ? $val[0]."..." : $val[0]; } //Goi ham $str = "Hàm cắt chuỗi Unicode với php"; echo cut_title($str,10); Code 3: Mã: // function catchuoi() 2 tham số: chuỗi input và vị trí cắt function catchuoi($chuoi,$gioihan){ // nếu độ dài chuỗi nhỏ hơn hay bằng vị trí cắt // thì không thay đổi chuỗi ban đầu if(strlen($chuoi)<=$gioihan) { return $chuoi; } else{ /* so sánh vị trí cắt với kí tự khoảng trắng đầu tiên trong chuỗi ban đầu tính từ vị trí cắt nếu vị trí khoảng trắng lớn hơn thì cắt chuỗi tại vị trí khoảng trắng đó */ if(strpos($chuoi," ",$gioihan) > $gioihan){ $new_gioihan=strpos($chuoi," ",$gioihan); $new_chuoi = substr($chuoi,0,$new_gioihan)."..."; return $new_chuoi; } // trường hợp còn lại không ảnh hưởng tới kết quả $new_chuoi = substr($chuoi,0,$gioihan)."..."; return $new_chuoi; } } Code 4: Mã: function cut_string($str,$len,$more){ 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; } Nguồn: http://www.nhatnghe.com/forum/showthread.php?t=174781