首頁  >  文章  >  後端開發  >  截取中文字串PHP程式碼

截取中文字串PHP程式碼

WBOY
WBOY原創
2016-07-25 08:46:07943瀏覽
  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 < $strlen; $i )
  25. {
  26. if ( $i >= $start && $i < ( $start $sublen ) )
  27. {
  28. if ( ord ( substr ( $string, $i, 1 ) ) > 129 )
  29. {
  30. $tmpstr .= substr ( $string, $i, 2 );
  31. }
  32. else
  33. {
  34. $tmpstr .= substr ( $string, $i, 1 );
  35. }
  36. }
  37. if ( ord ( substr ( $string, $i, 1 ) ) > 129 ) $i ;
  38. }
  39. if ( strlen ( $tmpstr ) < $strlen ) $tmpstr .= "...";
  40. return $tmpstr;
  41. }
  42. }
复制代码

PHP


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn