当前位置:首页 > PHP教程 > php函数 > 列表

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

发布:smiling 来源: PHP粉丝网  添加日期:2021-05-10 21:53:36 浏览: 评论:0 

这篇文章主要介绍了自己写的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. } 
  19. /* from Internet, author unknown */ 
  20. if (!function_exists('mb_substr')) { 
  21.     function mb_substr($str, $start, $len = '', $encoding="UTF-8"){ 
  22.         $limit = strlen($str); 
  23.  
  24.         for ($s = 0; $start > 0;--$start) {// found the real start 
  25.             if ($s >= $limit) 
  26.                 break; 
  27.  
  28.             if ($str[$s] <= "\x7F") 
  29.                 ++$s; 
  30.             else { 
  31.                 ++$s; // skip length 
  32.  
  33.                 while ($str[$s] >= "\x80" && $str[$s] <= "\xBF") 
  34.                     ++$s; 
  35.             } 
  36.         } 
  37.  
  38.         if ($len == '') 
  39.             return substr($str, $s); 
  40.         else 
  41.             for ($e = $s; $len > 0; --$len) {//found the real end 
  42.                 if ($e >= $limit) 
  43.                     break; 
  44.  
  45.                 if ($str[$e] <= "\x7F") 
  46.                     ++$e; 
  47.                 else { 
  48.                     ++$e;//skip length 
  49.  
  50.                     while ($str[$e] >= "\x80" && $str[$e] <= "\xBF" && $e < $limit) 
  51.                         ++$e; 
  52.                 } 
  53.             } 
  54.  
  55.         return substr($str, $s, $e - $s); 
  56.     } 
  57. }

Tags: mb_strlen mb_substr

分享到: