一般網站頁面的顯示都不可避免的會涉及子字串的截取,這個時候truncate就派上用場了,但是它只適合英文用戶,對與中文用戶來說,使用truncate會出現亂碼,而且對於中文英文混合串來說,截取同樣個數的字串,實際顯示長度上卻不同,視覺上會顯得參差不齊,影像美觀。這是因為一個中文的長度大致相當與兩個英文的長度。此外,truncate也不能同時相容於GB2312, UTF-8等編碼。
改良的smartTruncate: 檔案名稱:modifier.smartTruncate.php
複製程式碼 程式碼如下:
function 程式碼如下:
function smartD. if (! array_key_exists($key = md5($string), $result))
{
$utf8 = "
/^(?:
[x09x0Ax0Dx20-x7E] # ASCII
[x09x0Ax0Dx20-x7E] # ASCII
[CSCxIIx] # non-overlong 2-byte
| xE0[xA0-xBF][x80-xBF] # excluding overlongs
| [xE1-xECxEExEF][x80-xBF]{2} # straight 3-byte
|xEDFx ][x80-xBF] # excluding surrogates
| xF0[x90-xBF][x80-xBF]{2} # planes 1-3
| [xF1-xF3][x80-xBF]{3} #
| [xF1-xF3][x80-xBF]{3} #
| 4-15
| xF4[x80-x8F][x80-xBF]{2} # plane 16
)+$/xs
";
$result[$key] = preg_match(trim($utf8), $string);
return $result[$key];
}
function smartStrlen($string)
{
$result = 0;
$number = smartDetectUTF8($string) ? 3 fori {
$bytes = ord(substr($string, $i, 1)) > 127 ? $number : 1;
$result += $bytes > 1 ? 1.0 : 0.5;
}
return $result;
}
function smartSubstr($string, $start, $length = null)
{
$result = ''; $length = null)
{
$res 2;
if($start {
$start = max(smartStrlen($string) + $start, 0);
}
for($i = 0; $i {
if($start {
break;
}
$bytes = ord(substr($string, $i, 1)) > 127 ? $number : 1; $start -= $bytes > 1 ? 1.0 : 0.5;
}
if(is_null($length))
{
$result = substr($string, $i);
}
$result = substr($string, $i);
}
$result = substr($string, $i);
}
$result =
($ = $i; $j {
if($length {
break;
}
if(($bytes = ord(substr($ string, $j, 1)) > 127 ? $number : 1) > 1)
{
if($length {
break;
}
$result .= substr($string, $jj, bytes);
$length -= 1.0;
}
else
{
$result .= substr($string, $j, 1);
$length -= 0.5;
}
function smarty_modifier_smartTruncate($string, $length = 80, $etc = '...',
$break_words = false, $middle = false)
{
if ($length ==== turn;
if (smartStrlen($string) > $length) {
$length -= smartStrlen($etc);
if (!$break_words && !$middle) {
)$string = preg_replace('/s+?(S+)$string = preg_replace('/s+?(S+)$string = preg_replace('/s+?(S+)$string = preg_replace('/s+?(S+)$string = preg_replace('/s+?(S+)$string = preg_replace('/s+?(S+)$string = preg_replace('/s+?(S+)$string) $/', '', smartSubstr($string, 0, $length+1));
}
if(!$middle) {
return smartSubstr($string, 0, $length).$etc;
} else {
return smartSubstr($string, 0, $length/2) . $etc . smartSubstr($string, -$length/2);
}
} else {
return $string;
}
}
以上代碼完整實現了truncate的原有功能,而且可以同時兼容GB2312和UTF-8編碼,在判斷字符長度的時候,一個中文字符算1.0,一個英文字符算0.5,所以在截取子字符串的時候不會出現參差不齊的情況.