Home > php教程 > PHP源码 > php 计算中英文混合字符串的长度

php 计算中英文混合字符串的长度

WBOY
Release: 2016-06-08 17:29:42
Original
1116 people have browsed it

php 计算中英文混合字符串的长度

<script>ec(2);</script>


echo ccStrLen($str),'


';
echo ccStrLeft($str,3);
function ccStrLeft($str,$len) #从左边截取中英文混合字符串
{
$ascLen=strlen($str);   if($ascLen $hasCC=ereg("[xA1-xFE]",$str); #同上
$hasAsc=ereg("[x01-xA0]",$str);
if(!$hasCC) return substr($str,0,$len);
if(!$hasAsc)
if($len & 0x01) #如果长度是奇数
return substr($str,0,$len+$len-2);
else
return substr($str,0,$len+$len);
$cind=0;$flag=0;
while($cind {
if(ord(substr($str,$cind,1)) $cind++;
}
if($flag & 0x01)
return substr($str,0,$len);
else
return substr($str,0,$len-1);
}

function ccStrLen($str) #计算中英文混合字符串的长度
{
$ccLen=0;
$ascLen=strlen($str);
$ind=0;
$hasCC=ereg("[xA1-xFE]",$str); #判断是否有汉字
$hasAsc=ereg("[x01-xA0]",$str); #判断是否有ASCII字符
if($hasCC && !$hasAsc) #只有汉字的情况
return strlen($str)/2;
if(!$hasCC && $hasAsc) #只有Ascii字符的情况
return strlen($str);
for($ind=0;$ind {
if(ord(substr($str,$ind,1))>0xa0)
{
$ccLen++;
$ind++;
}
else
{
$ccLen++;
}
}
return $ccLen;
}


function cs($str) 
{
    $ccLen=0;
    $ascLen=strlen($str);
    $ind=0;
    for($ind=0;$ind     {
        if(ord(substr($str,$ind,1))>0xa0)
        {
            $ccLen++;
            $ind++;
        }
        else
        {
            $ccLen++;
        }
    }
    return $ccLen;
}

Related labels:
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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template