php字符串截取函数,支持中英文混体

php字符串截取函数,支持中英文混体,以前我们截取字符串都会用php自带的函数,今天我来看一下一款字符串截取函数,支持中英文混体的php代码实例吧.

php字符串截取函数代码如下:

  1. function cutstr($string, $sublen=10, $start = 0, $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. //if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen))."...";
  8. return join('', array_slice($t_string[0], $start, $sublen));
  9. }
  10. else
  11. {
  12. $start = $start*2;
  13. $sublen = $sublen*2;
  14. $strlen = strlen($string);
  15. $tmpstr = '';
  16. for($i=0; $i<$strlen; $i++)
  17. {
  18. if($i>=$start && $i<($start+$sublen))
  19. {
  20. if(ord(substr($string, $i, 1))>129) $tmpstr.= substr($string, $i, 2);
  21. else $tmpstr.= substr($string, $i, 1);
  22. }
  23. if(ord(substr($string, $i, 1))>129) $i++;
  24. }//开源软件:phpfensi.com
  25. //if(strlen($tmpstr)<$strlen ) $tmpstr.= "...";
  26. return $tmpstr;
  27. }
  28. }