Discuz教程网

PHP 字符串编码截取函数(兼容utf-8和gb2312)

[复制链接]
authicon dly 发表于 2011-9-5 20:24:35 | 显示全部楼层 |阅读模式
代码如下:

  1. //截取字符串长度。支持utf-8和gb2312编码。若为gb2312,先将其转为utf-8,在utf-8的基础上截取然后再转换回来
  2. function cut_string($str,$from=1,$length=10,$code='utf-8',$rear='...'){
  3. if($code!='utf-8'){//总是将字符串转为utf-8编码
  4. $str=iconv($code,'utf-8',$str);
  5. }
  6. $str_len=mb_strlen($str,'utf-8');//字符串的长度
  7. if($from>$str_len){//如果截取开始位置大于字符串长度,截取后面$length个
  8. $from=$str_len-$length+1;
  9. $from=($from<1?1:$from);
  10. }
  11. //兼容ucs-4编码
  12. $i=0;//字节计数
  13. $from_i=0;//开始截取的字节位置
  14. $from_len=0;//开始截取的字符位置
  15. $tag=true;//标志$from_len是否已经被赋值
  16. for($temp_len=0;($temp_len-$from_len<$length)||$tag;$temp_len++){
  17. $byte_code=ord(substr($str,$i,1));//一个字节的编码
  18. if($temp_len+1==$from){//记录开始截取的开始字节位置
  19. $from_i=$i;$from_len=$temp_len;$tag=false;
  20. }
  21. if($byte_code>=0&&$byte_code<128){//字符是占用几个字节,utf-8是变长编码,根据每个字符的第一个字节可判断出该字符占几个字节
  22. $i++;
  23. }
  24. if($byte_code>191&&$byte_code<224){
  25. $i+=2;
  26. }
  27. if($byte_code>223&&$byte_code<240){
  28. $i+=3;
  29. }
  30. if($byte_code>239&&$byte_code<248){
  31. $i+=4;
  32. }
  33. if($byte_code>248&&$byte_code<252){
  34. $i+=5;
  35. }
  36. if($byte_code>252&&$byte_code<255){
  37. $i+=6;
  38. }
  39. }
  40. return iconv('utf-8',$code,substr($str,$from_i,$i-$from_i).$rear);
  41. }
复制代码







上一篇:PHP 购物车的例子
下一篇:配置Apache2.2+PHP5+CakePHP1.2+MySQL5运行环境
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

1314学习网 ( 浙ICP备10214163号 )

GMT+8, 2025-5-2 04:59

Powered by Discuz! X3.4

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表