[PHP] 如何切割中文標題
May 18th, 2007 by appleboy 參觀者:1,501Views 機器人:610Views
今天看到酷!學園討論區,php版有人問說要如何切割中文字,結果我自己以前弄的一個function就貼了上去,如下
後來有人回應,這個function只能用在 big5底下,結果我測試了一下,的確只能用在big5底下,所以我又去官方網看了一下 php.net
發現底下這個function可以用在 big5 或者是 utf-8底下都ok
// String intercept By Bleakwind
// utf-8:$byte=3 | gb2312:$byte=2 | big5:$byte=2
function bite_str($string, $start, $len, $byte=3)
{
$str = "";
$count = 0;
$str_len = strlen($string);
for ($i=0; $i<$str_len; $i++) {
if (($count+1-$start)>$len) {
$str .= "...";
break;
} elseif ((ord(substr($string,$i,1)) <= 128) && ($count < $start)) {
$count++;
} elseif ((ord(substr($string,$i,1)) > 128) && ($count < $start)) {
$count = $count+2;
$i = $i+$byte-1;
} elseif ((ord(substr($string,$i,1)) <= 128) && ($count >= $start)) {
$str .= substr($string,$i,1);
$count++;
} elseif ((ord(substr($string,$i,1)) > 128) && ($count >= $start)) {
$str .= substr($string,$i,$byte);
$count = $count+2;
$i = $i+$byte-1;
}
}
return $str;
}
// utf-8:$byte=3 | gb2312:$byte=2 | big5:$byte=2
function bite_str($string, $start, $len, $byte=3)
{
$str = "";
$count = 0;
$str_len = strlen($string);
for ($i=0; $i<$str_len; $i++) {
if (($count+1-$start)>$len) {
$str .= "...";
break;
} elseif ((ord(substr($string,$i,1)) <= 128) && ($count < $start)) {
$count++;
} elseif ((ord(substr($string,$i,1)) > 128) && ($count < $start)) {
$count = $count+2;
$i = $i+$byte-1;
} elseif ((ord(substr($string,$i,1)) <= 128) && ($count >= $start)) {
$str .= substr($string,$i,1);
$count++;
} elseif ((ord(substr($string,$i,1)) > 128) && ($count >= $start)) {
$str .= substr($string,$i,$byte);
$count = $count+2;
$i = $i+$byte-1;
}
}
return $str;
}
reference:點我
不過有人說 利用 mb_substr 會更好我自己測試如下
如果要使用 big5 就把 UTF-8 改成 big-5,或找是可以在最前面加上
mb_internal_encoding("UTF-8");
$string = "0123456789";
$mystring = mb_substr($string,5,1);
echo $mystring;
$string = "0123456789";
$mystring = mb_substr($string,5,1);
echo $mystring;
隨機主題

mb_系列的函数确实是正解。
不过若系统中未安装mb扩展,使用preg系列正则表达式函数来改写你之前提供的使用循环方式判断的函数也是比较好的选择,速度虽然没有mb快,但是会较之循环方式增进很多。