提供个等长中文截取函数

字体大小: 中小 标准 ->行高大小: 标准
一般我们截取字符串,目的是在列表时标题保持长度相等,但是纯英文截取时候和纯中文截取时候,长度会有很大差异,汉字占两个字符长度的。。。。。。
所以偶弄的这个是等长截取
  1. <?php
  2. include('CutString.php');
  3. //假设要从第二个字符开始截取10个汉字长度的字符串

  4. //情况一:纯中文字符串
  5. $_S1 = '我是中国人我爱我的祖国';

  6. //情况二:英文或数字符号字符串
  7. $_S2 = 'abcdefg1234567!@#$%^^&**(()_';

  8. //情况三:混合中文字符串
  9. $_S3 = '我是boy1234*%混合字符串';

  10. //看看三次截取结果长度,是等长的
  11. echo CutString($_S1, 10,2,1);
  12. echo '<BR>';
  13. echo CutString($_S2, 10,2,1);
  14. echo '<BR>';
  15. echo CutString($_S3, 10,2,1);

  16. /***
  17. 中国人我爱我的祖国..
  18. efg1234567!@#$%^^&*..
  19. boy1234*%混合字符串..
  20. ***/
  21. ?>
复制代码
默认位utf8编码,$_Encode随便设置则为gb2312编码

函数代码如下:
  1. <?php
  2. /***************************************************************************
  3. * CutString.php
  4. * ------------------------------
  5. * Date : Oct 20, 2005
  6. * Run : Php4.1.1, Php5.0
  7. * Copyright : (C) 2005 - DreamSoft Co.,Ltd.
  8. * Mail : Dream@Dreamsoft.Ca
  9. * Author : Egmax
  10. *
  11. * 作用:中文截取
  12. *
  13. *
  14. ***************************************************************************/

  15. function CutString($_String, $_Length, $_Start=0, $_Encode='UTF-8')
  16. {
  17. $v = 0;
  18. if($_Encode == 'UTF-8')
  19. {
  20. $_Pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
  21. preg_match_all($_Pa, $_String, $_Rarray);
  22. $_SLength = count($_Rarray[0]);
  23. if($_SLength < $_Length) return $_String;
  24. for($i=$_Start; $i<$_SLength; $i++)
  25. {
  26. if($v >= $_Length * 2 - 1) return $_RS.'..';
  27. if(ord($_Rarray[0][$i]) > 129) $v += 2;
  28. else $v++;
  29. $_RS .= $_Rarray[0][$i];
  30. }
  31. } else {
  32. $_Start = $_Start * 2;
  33. $_Length = $_Length * 2;
  34. $_Len = strlen($_String);
  35. if($_Len < $_Length) return $_String;
  36. $_Rstring= '';
  37. for($i=$_Start; $i<$_Len; $i++)
  38. {
  39. if($v >= $_Length - 1) return $_Rstring.'..';
  40. if(ord(substr($_String, $i, 1)) > 129) { $_Rstring .= substr($_String, $i, 2); $v += 2; $i++; }
  41. else { $_Rstring .= substr($_String, $i, 1); $v++; }
  42. }
  43. return $_Rstring.'..';
  44. }
  45. }

  46. ?>
复制代码
根据字体的不同可能看起来不等长,比如村子的字体,英文显得长点。。

此文章由 http://www.ositren.com 收集整理 ,地址为: http://www.ositren.com/htmls/29848.html