当前位置:编程学习 > php >>

PHP一个实用的截取混合字符串的函数

  1. function cut_str($string, $start,$sublen, $code = 'UTF-8')
  2. {
  3. if($code == 'UTF-8')
  4. {
  5. $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]/";
  6. preg_match_all($pa, $string, $t_string);
  7.  
  8. if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen))."...";
  9. return join('', array_slice($t_string[0], $start, $sublen));
  10. }
  11. else
  12. {
  13. $start = $start*2;
  14. $sublen = $sublen*2;
  15. $strlen = strlen($string);
  16. $tmpstr = '';
  17. //www.zhaoxi.org 朝夕网
  18. for($i=0; $i< $strlen; $i++)
  19. {
  20. if($i>=$start && $i< ($start+$sublen))
  21. {
  22. if(ord(substr($string, $i, 1))>129)
  23. {
  24. $tmpstr.= substr($string, $i, 2);
  25. }
  26. else
  27. {
  28. $tmpstr.= substr($string, $i, 1);
  29. }
  30. }
  31. if(ord(substr($string, $i, 1))>129) $i++;
  32. }
  33. if(strlen($tmpstr)< $strlen ) $tmpstr.= "...";
  34. return $tmpstr;
  35. }
  36. }
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,