欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

截取中文字符串PHP代码

程序员文章站 2022-04-26 19:58:49
...
  1. /**
  2. *
  3. * 中文字符串截取
  4. * @param string $string
  5. * @param int $sublen
  6. * @param int $start
  7. * @param string $code
  8. */
  9. function substr_zh ( $string, $sublen, $start = 0, $code = 'UTF-8' )
  10. {
  11. if ( $code == 'UTF-8' )
  12. {
  13. $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]/";
  14. preg_match_all ( $pa, $string, $t_string );
  15. if ( count ( $t_string[0] ) - $start > $sublen ) return join ( '', array_slice ( $t_string[0], $start, $sublen ) ) . "...";
  16. return join ( '', array_slice ( $t_string[0], $start, $sublen ) );
  17. }
  18. else
  19. {
  20. $start = $start * 2;
  21. $sublen = $sublen * 2;
  22. $strlen = strlen ( $string );
  23. $tmpstr = '';
  24. for ( $i = 0; $i {
  25. if ( $i >= $start && $i {
  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 ) return $tmpstr;
  38. }
  39. }
复制代码

PHP