最近忙于項目,分享的時間就少了,自上次發布“Phpcms V9內容頁show模板調用標簽解讀”又已半月!在最近的項目中,發現官方最新版PHPCMS V9.3.1 正式版已經有日語的語言包,說明了PC的一個動向:國際化趨向。不過日語這個語言包還只是預覽,沒有日化到位。
今天在這里分享最近在英文網站中優化的一個小改進:Phpcms V9截取字符函數改進:截取英文更精確,具體方法來自PC官方論壇,分享在此。
官方默認的str_cut()截取的字符統計長度不精準,特別是在中英文字符混搭的時候,調用列表會出現問題,采用【拽拽焱】分享的方法,可以將長度偏差在2個字符內,很不錯,先贊一個!
具體代碼:
/*** 字符截取 支持UTF8/GBK www.49028c.com* @param $string* @param $length* @param $dot*/function str_cut($string, $length, $dot = '') {$strlen = strlen($string);if($strlen/2 <= $length) return $string;$string = str_replace(array(' ',' ',' ',' ', '&', '"', ''', '“', '”', '—', '<', '>', '·', '…'), array(' ',' ',' ',' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);$strcut = '';$n = $tn = $noc = 0;if(strtolower(CHARSET) == 'utf-8') {while($n < $strlen) {$t = ord($string[$n]);if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {$tn = 1; ++$n; $noc += 0.5;} elseif(194 <= $t && $t <= 223) {$tn = 2; $n += 2; $noc += 1;} elseif(224 <= $t && $t <= 239) {$tn = 3; $n += 3; $noc += 1;} elseif(240 <= $t && $t <= 247) {$tn = 4; $n += 4; $noc += 1;} elseif(248 <= $t && $t <= 251) {$tn = 5; $n += 5; $noc += 1;} elseif($t == 252 || $t == 253) {$tn = 6; $n += 6; $noc += 1;} else {++$n;}if($noc >= $length) {if($n < $strlen) ++$noc;break;}}} else {while($n < $strlen) {if(ord($string[$n]) > 127) {$tn = 2; $n += 2; $noc += 1;} else{$tn = 1; ++$n; $noc += 0.5;}if($noc >= $length) {if($n < $strlen) ++$noc;break;}}}if($noc > $length && !empty($dot)) {$n -= $tn;$strcut = substr($string, 0, $n);$strcut .= $dot;}else{$strcut = substr($string, 0, $n);}$strcut = str_replace(array('&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), array('&', '"', ''', '“', '”', '—', '<', '>', '·', '…'), $strcut);return $strcut;}
新聞熱點
疑難解答