2009年8月26日 星期三

php 截斷字數... 的function

function cut_str($str, $maxlen,$type=1) {
$i = 0; $f = true;$k=0;
$len = strlen($str);
while ($i <= $len) {
if (ord($str{$i}) < 0x80) { $i++; $k++;}
elseif (ord($str{$i}) < 0xe0) { $i += 2; $k++;}
elseif (ord($str{$i}) < 0xf0) { $i += 3; $k++;}
elseif (ord($str{$i}) < 0xf8) { $i += 4; $k++;}
elseif (ord($str{$i}) < 0xfc) { $i += 5; $k++;}
elseif (ord($str{$i}) < 0xfe) { $i += 6; $k++;}
if (($k >= $maxlen) && $f) {
$str = substr($str, 0, $i);
$f = false;
}
if (($k > $maxlen) && ($i <=$len)) {
if ($type != 3){ //skye 11/7加上此判斷,type=3時不需要加...
$str .= "...";
break;
}
}
}
if($type == 1 || $type == 3)
return $str;
else if($type == 2)
return $k-1;
}

【下列文章您可能也有興趣】

沒有留言: