PHP Chinese string interception function supports multiple encodings

WBOY
Release: 2016-07-25 09:04:23
Original
910 people have browsed it
  1. /*

  2. * @todo Chinese interception, support gb2312, gbk, utf-8, big5
  3. * @http://bbs.it-home.org
  4. * @param string $str The string to be intercepted
  5. * @param int $start The interception starting position
  6. * @param int $length The interception length
  7. * @param string $charset utf-8|gb2312|gbk|big5 encoding
  8. * @ param $suffix whether to add a suffix
  9. */

  10. function csubstr($str, $start=0, $length, $charset="utf-8", $suffix=true)

  11. {
  12. if(function_exists("mb_substr"))
  13. return mb_substr($str, $start, $length, $charset);
  14. $re['utf-8'] = "/[x01-x7f]|[xc2-xdf ][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
  15. $re['gb2312'] = "/[x01 -x7f]|[xb0-xf7][xa0-xfe]/";
  16. $re['gbk'] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
  17. $re ['big5'] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
  18. preg_match_all($re[$charset], $str, $match) ;
  19. $slice = join("",array_slice($match[0], $start, $length));
  20. if($suffix) return $slice."…";
  21. return $slice;
  22. }
  23. ?> ;
Copy the code

The above code looks awesome, if you know the regular rules of PHP, it is quite powerful. Copy the above code and test it on your machine. Doing more will help you quickly improve your programming level.



source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template