Home > Backend Development > PHP Tutorial > How to correctly count Chinese characters? _PHP Tutorial

How to correctly count Chinese characters? _PHP Tutorial

WBOY
Release: 2016-07-13 17:12:17
Original
927 people have browsed it

PHP code:------------------------------------------------ ----------------------------------
function ccStrLen($str) #Calculate mixed Chinese and English strings Length
{
$ccLen=0;
$ascLen=strlen($str);
$ind=0;
$hasCC=ereg("[xA1-xFE]",$ str); #Determine whether there are Chinese characters
$hasAsc=ereg("[x01-xA0]",$str); #Determine whether there are ASCII characters
if($hasCC && !$hasAsc) #Only Chinese characters Case
return strlen($str)/2;
if(!$hasCC && $hasAsc) #Only Ascii characters case
return strlen($str);
for($ind=0 ;$ind<$ascLen;$ind++)
{
if(ord(substr($str,$ind,1))>0xa0)
{
$ccLen++;
$ ind++;
}
else
{
$ccLen++;
}
}
return $ccLen;
}
function ccStrLeft($str,$len ) #Intercept the Chinese and English mixed string from the left
{
$ascLen=strlen($str); if($ascLen<=$len) return $str;
$hasCC=ereg("[xA1 -xFE]",$str); #Same as above
$hasAsc=ereg("[x01-xA0]",$str);
if(!$hasCC) return substr($str,0,$len );
if(!$hasAsc)
if($len & 0x01) #If the length is an odd number
return substr($str,0,$len+$len-2);
else
return substr($str,0,$len+$len);
$cind=0;$flag=0;
while($cind<$ascLen)
{
if(ord (substr($str,$cind,1))<0xA1) $flag++;
$cind++;
}
if($flag & 0x01)
return substr($str,0, $len);
else
return substr($str,0,$len-1);
}
------------------ -------------------------------------------------- ------------
____________________
┌──┬──┐
│ 

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/629497.htmlTechArticlePHP code:------------------------ -------------------------------------------------- --------- function ccStrLen($str) #Calculate the length of mixed Chinese and English strings { $ccLen=0; $ascLen=strle...
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