PHP截取中文字符串
當(dāng)前位置:點(diǎn)晴教程→知識管理交流
→『 技術(shù)文檔交流 』
<?php //一個漢字占兩個字母字節(jié)大小 $str='我們在盤下建立資料夾在依照不同瀏覽器對應(yīng)到不同的子目路以為例我們將資料夾對'; echo strlen($str),','; //出現(xiàn)亂碼 $s=substr($str,9); echo $s,"\r\n"; $s=cn_substr($str,9); echo $s,"\r\n"; //這樣就沒有亂碼 $s=substr($str,10); echo $s,"\r\n"; $s=' Cache IE9 , , , D'; echo strlen($s); function cn_substr($title,$start,$len="",$magic=true) { $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) { $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; } } return substr($title,$start,$length); } 該文章在 2012/4/3 22:46:58 編輯過 |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |