php支持gb2312,uft-8中英文字符截取函数

  1. <?php
  2. //截取gb2312中文字符串
  3. function mysubstr($str, $start, $len) {
  4. $tmps教程tr = "";
  5. $strlen = $start + $len;
  6. for($i = 0; $i < $strlen; $i++) {
  7. if(ord(substr($str, $i, 1)) > 0xa0) {
  8. $tmpstr .= substr($str, $i, 2);
  9. $i++;
  10. } else
  11. $tmpstr .= substr($str, $i, 1);
  12. }
  13. return $tmpstr;
  14. }
  15. ?>
  16. <?php
  17. //截取utf8字符串
  18. function utf8substr($str, $from, $len)
  19. {
  20. return preg_replace('#^(?:[x00-x7f]|[xc0-xff][x80-xbf]+){0,'.$from.'}'.
  21. '((?:[x00-x7f]|[xc0-xff][x80-xbf]+){0,'.$len.'}).*#s',
  22. '$1',$str);
  23. }
  24. ?>

把上面两个例子整合了

  1. /*
  2. utf-8、gb2312都支持的汉字截取函数
  3. cut_str(字符串, 截取长度, 开始长度, 编码);
  4. 编码默认为 utf-8
  5. 开始长度默认为 0
  6. */
  7. function cut_str($string, $sublen, $start = 0, $code = 'utf-8')
  8. {
  9. if($code == 'utf-8')
  10. {
  11. $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]/";
  12. preg_match_all($pa, $string, $t_string);
  13. if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen))."...";
  14. return join('', array_slice($t_string[0], $start, $sublen));
  15. }
  16. else
  17. {
  18. $start = $start*2;
  19. $sublen = $sublen*2;
  20. $strlen = strlen($string);
  21. $tmpstr = '';
  22. for($i=0; $i< $strlen; $i++)
  23. {
  24. if($i>=$start && $i< ($start+$sublen))
  25. {
  26. if(ord(substr($string, $i, 1))>129)
  27. {
  28. $tmpstr.= substr($string, $i, 2);
  29. }
  30. else
  31. {
  32. $tmpstr.= substr($string, $i, 1);
  33. }
  34. }
  35. if(ord(substr($string, $i, 1))>129) $i++;
  36. }
  37. if(strlen($tmpstr)< $strlen ) $tmpstr.= "...";
  38. return $tmpstr;
  39. }
  40. }
  41. $str = "abcd需要截取的字符串";
  42. echo cut_str($str, 8, 0, 'gb2312');
  43. ?>