现在的位置: 首页 > 综合 > 正文

PHP 截取 中文

2013年03月11日 ⁄ 综合 ⁄ 共 1015字 ⁄ 字号 评论关闭
函数巧妙地运用了正则表达式, 用起来很方便, 就像 substr 的用法一样, 可以正向截取也可反相截取, 思路值得学习.

PHP代码:
  1. <?php
  2. function c_substr($string$from$length = null){
  3.     preg_match_all('/[x80-xff]?./'$string$match);
  4.     if(is_null($length)){
  5.         $result = implode(''array_slice($match[0]$from));
  6.     }else{
  7.         $result = implode(''array_slice($match[0]$from$length));
  8.     }
  9.     return $result;
  10. }
  11. $str = "zhon华人min共和guo";
  12. $from = 3;
  13. $length = 7;
  14. echo(c_substr($str$from$length));
  15. // 输出: n华人min共
  16. //还有utf-8的
  17. /*
  18. Regarding windix's function to handle UTF-8 strings:
  19. one can use the "u" modifier on the regular expression so that the pattern string is treated as UTF-8
  20. (available from PHP 4.1.0 or greater on Unix and from PHP 4.2.3 on win32).
  21. This way the function works for other encodings too (like Greek for example).
  22. The modified function would read like this:
  23. */
  24. function utf8_substr($str,$start) {
  25. $null = "";
  26.    preg_match_all("/./u"$str$ar);
  27.    if(func_num_args() >= 3) {
  28.        $end = func_get_arg(2);
  29.        return join($nullarray_slice($ar[0],$start,$end));
  30.    } else {
  31.        return join($nullarray_slice($ar[0],$start));
  32.    }
  33. }
  34. ?>

抱歉!评论已关闭.