直接上代码,原理见末尾原文链接:
<!-- lang: php -->
<?php
function 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("你是我的小苹果");