Home >Backend Development >PHP Tutorial >php计算中文字符串的长度

php计算中文字符串的长度

WBOY
WBOYOriginal
2016-06-23 13:38:041238browse

<?phpfunction mbstrlen($str,$encoding="utf8"){    if (($len = strlen($str)) == 0) {        return 0;    }    $encoding = strtolower($encoding);    if ($encoding == "utf8" or $encoding == "utf-8") {        $step = 3;    } elseif ($encoding == "gbk" or $encoding == "gb2312") {        $step = 2;    } else {        return false;    }    $count = 0;    for ($i=0; $i<$len; $i++) {        $count++;        //如果字节码大于127,则根据编码跳几个字节        if (ord($str{$i}) >= 0x80) {            $i = $i + $step - 1;//之所以减去1,因为for循环本身还要$i++        }    }    return $count;}echo mbstrlen(iconv("utf-8","gbk","你是我的小苹果"),"gbk");echo mbstrlen("你是我的小苹果");

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn