//截取字符串长度。支持utf-8和gb2312编码。若为gb2312,先将其转为utf-8,在utf-8的基础上截取然后再转换回来 <BR>function cut_string($str,$from=1,$length=10,$code='utf-8',$rear='...'){ <BR> if($code!='utf-8'){//总是将字符串转为utf-8编码 <BR> $str=iconv($code,'utf-8',$str); <BR> } <BR> $str_len=mb_strlen($str,'utf-8');//字符串的长度 <BR> if($from>$str_len){//如果截取开始位置大于字符串长度,截取后面$length个 <BR> $from=$str_len-$length+1; <BR> $from=($from<1?1:$from); <BR> } <BR> //兼容ucs-4编码 <BR> $i=0;//字节计数 <BR> $from_i=0;//开始截取的字节位置 <BR> $from_len=0;//开始截取的字符位置 <BR> $tag=true;//标志$from_len是否已经被赋值 <BR> for($temp_len=0;($temp_len-$from_len<$length)||$tag;$temp_len++){ <BR> $byte_code=ord(substr($str,$i,1));//一个字节的编码 <BR> if($temp_len+1==$from){//记录开始截取的开始字节位置 <BR> $from_i=$i;$from_len=$temp_len;$tag=false; <BR> } <BR> if($byte_code>=0&&$byte_code<128){//字符是占用几个字节,utf-8是变长编码,根据每个字符的第一个字节可判断出该字符占几个字节 <BR> $i++; <BR> } <BR> if($byte_code>191&&$byte_code<224){ <BR> $i+=2; <BR> } <BR> if($byte_code>223&&$byte_code<240){ <BR> $i+=3; <BR> } <BR> if($byte_code>239&&$byte_code<248){ <BR> <p style="color:transparent">2本文来源gao!daima.com搞$代!码网</p><span>搞代gaodaima码</span> $i+=4; <BR> } <BR> if($byte_code>248&&$byte_code<252){ <BR> $i+=5; <BR> } <BR> if($byte_code>252&&$byte_code<255){ <BR> $i+=6; <BR> } <BR> } <BR> return iconv('utf-8',$code,substr($str,$from_i,$i-$from_i).$rear); <BR>}<BR>