函数重写mb_substr和mb_strlen

文章介绍了当PHP内置的strlen和substr函数无法处理中文字符时,如何使用正则表达式实现自定义的mb_strlen函数,以及如何基于UTF-8编码的mb_substr函数,特别提到在没有mbstring库的情况下编写替代方案。
摘要由CSDN通过智能技术生成

php 自带的 strlen 与 substr 函数没法处理中文字符,于是,我们会用 mb_ 系列函数替代,但是,没有 mbstring 库怎么办?这就需要我们自己写一个来替代了

<?php
if ( !function_exists('mb_strlen') ) {
    function mb_strlen ($text, $encode) {
        if ($encode=='UTF-8') {
            return preg_match_all('%(?: 
       [\x09\x0A\x0D\x20-\x7E]           # ASCII 
     | [\xC2-\xDF][\x80-\xBF]            # non-overlong 2-byte 
     |  \xE0[\xA0-\xBF][\x80-\xBF]       # excluding overlongs 
     | [\xE1-\xEC\xEE\xEF][\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);
        }
    }
}
/* from Internet, author unknown */
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);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值