當網站使用UTF-8編碼時,使用下面的函數,可以防止擷取字串時,中文字被切掉一半的問題。
複製內容到剪貼板
代碼:
<?
function cutstr($string, $length) { //$string為原字串,$length為截取長度
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]/", $string, $info);
for($i=0; $i<count($info[0]); $i++) {
$wordscut .= $info[0][$i];
$j = ord($info[0][$i]) > 127 ? $j + 2 : $j + 1;
if ($j > $length - 3) {
return $wordscut."…";
}
}
return join('', $info[0]);;
}
//使用範例:
$text = "撰寫網誌內容記錄生活感想、嗜好、心情故事、或珍貴回憶。";
$text = cutstr($text,20);
echo "$text";
?>
[
本帖最後由 philxyz0316 於 2006-7-23 21:23 編輯 ]