栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > PHP

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

PHP 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

复制代码 代码如下:
if ( !function_exists('mb_strlen') ) {
 function mb_strlen ($text, $encode) {
  if ($encode=='UTF-8') {
   return preg_match_all('%(?:
       [x09x0Ax0Dx20-x7E]           # ASCII
     | [xC2-xDF][x80-xBF]            # non-overlong 2-byte
     |  xE0[xA0-xBF][x80-xBF]       # excluding overlongs
     | [xE1-xECxEExEF][x80-xBF]{2} # straight 3-byte
     |  xED[x80-x9F][x80-xBF]       # excluding surrogates
     |  xF0[x90-xBF][x80-xBF]{2}    # planes 1-3
     | [xF1-xF3][x80-xBF]{3}         # planes 4-15
     |  xF4[x80-x8F][x80-xBF]{2}    # plane 16
     )%xs',$text,$out);
  }else{
   return strlen($text);
  }
 }
}


if (!function_exists('mb_substr')) {
    function mb_substr($str, $start, $len = '', $encoding="UTF-8"){
        $limit = strlen($str);
 
        for ($s = 0; $start > 0;--$start) {// found the real start
            if ($s >= $limit)
                break;
 
            if ($str[$s] <= "x7F")
                ++$s;
            else {
                ++$s; // skip length
 
                while ($str[$s] >= "x80" && $str[$s] <= "xBF")
                    ++$s;
            }
        }
 
        if ($len == '')
            return substr($str, $s);
        else
            for ($e = $s; $len > 0; --$len) {//found the real end
                if ($e >= $limit)
                    break;
 
                if ($str[$e] <= "x7F")
                    ++$e;
                else {
                    ++$e;//skip length
 
                    while ($str[$e] >= "x80" && $str[$e] <= "xBF" && $e < $limit)
                        ++$e;
                }
            }
 
        return substr($str, $s, $e - $s);
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/46239.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号