Last active
July 16, 2018 09:18
-
-
Save zigo928/7986120c521bb48c05f319fa312e36ff to your computer and use it in GitHub Desktop.
获取中英文混合字符串长度
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function my_mb_strlen($value) | |
{ | |
// 计算单字节. | |
preg_match_all('/[a-zA-Z0-9_]/', $value, $single); | |
$single = count($single[0]) / 2; | |
// 多子节长度. | |
$double = str_word_count(preg_replace('([a-zA-Z0-9_])', '', $value)); | |
// 得出最终计算字符的长度 | |
$length = $single + $double; | |
return $length; | |
} | |
public static function mb_strlen($string) | |
{ | |
$n = $tn = $noc = 0; | |
$length = strlen($string); | |
while($n < strlen($string)) { | |
$t = ord($string[$n]); | |
if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) { | |
$tn = 1; $n++; $noc += 0.5; | |
} elseif(194 <= $t && $t <= 223) { | |
$tn = 2; $n += 2; $noc += 1; | |
} elseif(224 <= $t && $t <= 239) { | |
$tn = 3; $n += 3; $noc += 1; | |
} elseif(240 <= $t && $t <= 247) { | |
$tn = 4; $n += 4; $noc += 1; | |
} elseif(248 <= $t && $t <= 251) { | |
$tn = 5; $n += 5; $noc += 1; | |
} elseif($t == 252 || $t == 253) { | |
$tn = 6; $n += 6; $noc += 1; | |
} else { | |
$n++; | |
} | |
if($noc >= $length) { | |
break; | |
} | |
} | |
return intval(ceil($noc)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment