国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

舊題新貌:PHP截取中文字符串的問題

瀏覽:66日期:2024-02-02 18:27:58

以下代碼試用于GB2312編碼,截取中文字符串是PHP中一個頭疼的問題,解決方法是根據(jù)值是否大于等于128來判斷是否是雙字節(jié)字符,以避免出現(xiàn)亂碼的情況。但中英文混合、特殊符號等問題總是存在,現(xiàn)在寫一個比較全面的,僅供參考:

程序說明:1. len 參數(shù)以中文字符為標準,1len等于2個英文字符,為了形式上好看些2. 如果將magic參數(shù)設為false,則中文和英文同等看待,取絕對的字符數(shù)3. 特別適用于用htmlspecialchars()進行過編碼的字符串4. 能正確處理GB2312中實體字符模式(𖰰)

程序代碼:

function FSubstr($title,$start,$len='',$magic=true) {/** *; powered by Smartpig *; mailto:d.einstein@263.net */ $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) == '&lt;') { $cstep = 4; $length += 4; $i += 3; $realnum ++; if($magic) { $alen ++; } } else if(substr($title,$i,4) == '&gt;') { $cstep = 4; $length += 4; $i += 3; $realnum ++; if($magic) { $alen ++; } } else if(substr($title,$i,5) == '&amp;') { $cstep = 5; $length += 5; $i += 4; $realnum ++; if($magic) { $alen ++; } } else if(substr($title,$i,6) == '&quot;') { $cstep = 6; $length += 6; $i += 5; $realnum ++; if($magic) { $alen ++; } } else if(substr($title,$i,6) == '&#039;') { $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編碼下的代碼也貼出來

標簽: PHP
主站蜘蛛池模板: 宁明县| 三亚市| 石河子市| 河东区| 施秉县| 堆龙德庆县| 南和县| 江安县| 游戏| 建昌县| 黄山市| 团风县| 哈尔滨市| 武功县| 枣阳市| 华容县| 长岭县| 桃江县| 诸城市| 克拉玛依市| 东丽区| 绥德县| 和龙市| 深水埗区| 根河市| 北票市| 宝丰县| 隆尧县| 孝义市| 故城县| 肥乡县| 阿克| 丹巴县| 西吉县| 增城市| 永济市| 定安县| 四平市| 东阿县| 马公市| 安泽县|