以下程式碼試用於GB2312編碼,截取中文字串是PHP中一個頭痛的問題,解決方法是根據值是否大於等於128來判斷是否是雙字節字符,以避免出現亂碼的情況。但中英文混合、特殊符號等問題總是存在,現在寫一個比較全面的,僅供參考:
程序說明:
1. len 參數以中文字符為標準,1len等於2個英文字符,為了形式上好看些
2. 若將magic參數設為false,則中文和英文同等看待,取絕對的字元數
3. 特別適用於用htmlspecialchars()進行過編碼的字串
4. 能正確處理GB2312中實體字元模式(𖰰)
程式碼:
function FSubstr($title,$start,$len="",$magic=true)
{
/**
* powered by Smartpig
* mailto:[email protected]
*/
$length = 0;
if($len == "") $len = strlen($title);
//判斷起始為不正確位置
if($start > 0)
{
$cnum = 0;
for($i=0;$i<$start;$i++)
{
if(ord(substr($title,$i,1)) >= 128) $cnum ++;
}
if($cnum%2 != 0) $start--;
unset($cnum);
}
if(strlen($title)<=$len) return substr($title,$start,$len);
$alen = 0;
$blen = 0;
$realnum = 0;
for($i=$start;$i<strlen($title);$i++)
{
$ctype = 0;
$cstep = 0;
$cur = substr($title,$i,1);
if($cur == "&")
{
if(substr($title,$i,4) == "<")
{
$cstep = 4;
$length += 4;
$i += 3;
$realnum ++;
if($magic)
{
$alen ++;
}
}
else if(substr($title,$i,4) == ">")
{
$cstep = 4;
$length += 4;
$i += 3;
$realnum ++;
if($magic)
{
$alen ++;
}
}
else if(substr($title,$i,5) == "&")
{
$cstep = 5;
$length += 5;
$i += 4;
$realnum ++;
if($magic)
{
$alen ++;
}
}
else if(substr($title,$i,6) == """)
{
$cstep = 6;
$length += 6;
$i += 5;
$realnum ++;
if($magic)
{
$alen ++;
}
}
else if(substr($title,$i,6) == "'")
{
$cstep = 6;
$length += 6;
$i += 5;
$realnum ++;
if($magic)
{
$alen ++;
}
}
else if(preg_match("/&#(d+);/i",substr($title,$i,8),$match))
{
$cstep = strlen($match[0]);
$length += strlen($match[0]);
$i += strlen($match[0])-1;
$realnum ++;
if($magic)
{
$blen ++;
$ctype = 1;
}
}
}else{
if(ord($cur)>=128)
{
$cstep = 2;
$length += 2;
$i += 1;
$realnum ++;
if($magic)
{
$blen ++;
$ctype = 1;
}
}else{
$cstep = 1;
$length +=1;
$realnum ++;
if($magic)
{
if(ord($cur) >= 65 && ord($cur) <= 90)
{
$blen++;
}else{
$alen++;
}
}
}
}
if($magic)
{
if(($blen*2+$alen) == ($len*2)) break;
if(($blen*2+$alen) == ($len*2+1))
{
if($ctype == 1)
{
$length -= $cstep;
break;
}else{
break;
}
}
}else{
if($realnum == $len) break;
}
}
unset($cur);
unset($alen);
unset($blen);
unset($realnum);
unset($ctype);
unset($cstep);
return substr($title,$start,$length);
}
呵呵,一會兒把UTF-8編碼下的程式碼也貼出來