首页 > 语言 > PHP > 正文

自己写的php中文截取函数mb_strlen和mb_substr

2024-09-04 11:42:52
字体:
来源:转载
供稿:网友

这篇文章主要介绍了自己写的php中文截取函数mb_strlen和mb_substr,在服务器没mbstring库时可以使用本文函数代替,需要的朋友可以参考下

众所周知,php 自带的 strlen 与 substr 函数没法处理中文字符,于是,我们会用 mb_ 系列函数替代,但是,没有 mbstring 库怎么办?这就需要我们自己写一个来替代了,废话不多说,先上代码:

  1. if ( !function_exists('mb_strlen') ) { 
  2.  function mb_strlen ($text$encode) { 
  3.   if ($encode=='UTF-8') { 
  4.    return preg_match_all('%(?: 
  5.        [/x09/x0A/x0D/x20-/x7E]           # ASCII 
  6.      | [/xC2-/xDF][/x80-/xBF]            # non-overlong 2-byte 
  7.      |  /xE0[/xA0-/xBF][/x80-/xBF]       # excluding overlongs 
  8.      | [/xE1-/xEC/xEE/xEF][/x80-/xBF]{2} # straight 3-byte 
  9.      |  /xED[/x80-/x9F][/x80-/xBF]       # excluding surrogates 
  10.      |  /xF0[/x90-/xBF][/x80-/xBF]{2}    # planes 1-3 
  11.      | [/xF1-/xF3][/x80-/xBF]{3}         # planes 4-15 
  12.      |  /xF4[/x80-/x8F][/x80-/xBF]{2}    # plane 16 
  13.      )%xs',$text,$out); 
  14.   }else
  15.    return strlen($text); 
  16.   } 
  17.  } 
  18. /* from Internet, author unknown */ 
  19. if (!function_exists('mb_substr')) { 
  20.     function mb_substr($str$start$len = ''$encoding="UTF-8"){ 
  21.         $limit = strlen($str); 
  22.  
  23.         for ($s = 0; $start > 0;--$start) {// found the real start 
  24.             if ($s >= $limit
  25.                 break
  26.  
  27.             if ($str[$s] <= "/x7F"
  28.                 ++$s
  29.             else { 
  30.                 ++$s// skip length 
  31.  
  32.                 while ($str[$s] >= "/x80" && $str[$s] <= "/xBF"
  33.                     ++$s
  34.             } 
  35.         } 
  36.  
  37.         if ($len == ''
  38.             return substr($str$s); 
  39.         else 
  40.             for ($e = $s$len > 0; --$len) {//found the real end 
  41.                 if ($e >= $limit
  42.                     break
  43.  
  44.                 if ($str[$e] <= "/x7F"
  45.                     ++$e
  46.                 else { 
  47.                     ++$e;//skip length 
  48.  
  49.                     while ($str[$e] >= "/x80" && $str[$e] <= "/xBF" && $e < $limit
  50.                         ++$e
  51.                 } 
  52.             } 
  53.  
  54.         return substr($str$s$e - $s); 
  55.     } 
  56. }

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表