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

php计算中文字符串的长度

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-23 13:38:04
Original
1259 people have browsed it

<?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("你是我的小苹果");
Copy after login

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template