Home  >  Article  >  Backend Development  >  Intercept Chinese string PHP code

Intercept Chinese string PHP code

WBOY
WBOYOriginal
2016-07-25 08:46:07946browse
  1. /**
  2. *
  3. * Chinese string interception
  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


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn