//PHP中英文截取無亂碼
header(‘Content_type=text/php;charset=UTF-8’);
$str = ‘北京beijing大學’;
//關鍵在於判斷往後截多少個字節上,這是這個函數的核心
//此函數是用客串來判斷的,效率不高
//位運算效果會更好
//110x xxxx && 1110 0000 -> 1100 0000
//1110 xxxx && 1111 0000 -> 1110 0000
//位運算時不受英文字符最高位爲0的影響,只是在轉成字符串才受到影響
function utf8sub($str,$len){
if($len<0){
return ”;
}
$res = ”;
$offset = 0;
$chars = 0;
$count = 0;
$length = strlen($str);//待截取字符串的字節數
while($chars<$len && $offset<$length){
$high = decbin(ord(substr(
//重要突破,已經能夠判斷高位字節
if(strlen($high)<8){
$count = 1;
}elseif (substr($high,0,3) == ‘110’) {
$count = 2; //取兩個字節的長度
}elseif (substr($high,0,4) == ‘1110’) {
$count = 3; //取三個字節的長度
}elseif (substr($high,0,5) == ‘11110’) {
$count = 4;
}elseif (substr($high,0,6) == ‘111110’) {
$count = 5;
}elseif(substr($high,0,7)==’1111110’){
$count = 6;
}
$res .= substr($str,$offset,$count);
$chars +=1;
$offset += $count;
}
return $res;
}
echo utf8sub($str,5);
echo utf8sub($str,10);
中英文截取字符串無亂碼
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.