主要介绍两种字符集下(GBK,UTF-8)下,字符串长度的计算。
GBK字符串长度
function strlen_gbk($str) { $len = strlen($str); $i = 0; while ($i < $len) { if (preg_match("/^[" . chr(0xa1) . "-" . chr(0xff) . "]+$/", $str[$i])) { $i += 2; } else { $i += 1; } } return $i; }
UTF8字符串长度
<?php /** * 计算 UTF-8 字符串长度(忽略字节的方案) * * @param string $str * @return int */ function strlen_utf8($str) { $i = 0; $count = 0; $len = strlen($str); while ($i < $len) { $chr = ord($str[$i]); $count++; $i++; if ($i >= $len) { break; } if ($chr & 0x80) { $chr <<= 1; while ($chr & 0x80) { $i++; $chr <<= 1; } } } return $count; } $str = "http://blog.csdn.net/qq_16619037"; echo strlen_utf8($str); ?>