亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

php截取字符串之截取utf8或gbk編碼的中英文字符串示例

 更新時(shí)間:2014年03月12日 11:06:03   作者:  
php中自帶strlen是返回的字節(jié)數(shù),對(duì)于utf8編碼的中文返回時(shí)3個(gè),不滿足需求,下面給大家提供一個(gè)方法來(lái)完成這樣的功能

微博的發(fā)言有字?jǐn)?shù)限制,其計(jì)數(shù)方式是,中文算2個(gè),英文算1個(gè),全角字符算2個(gè),半角字符算1個(gè)。
php中自帶strlen是返回的字節(jié)數(shù),對(duì)于utf8編碼的中文返回時(shí)3個(gè),不滿足需求。
mb_strlen 可以根據(jù)字符集計(jì)算長(zhǎng)度,比如utf8的中文計(jì)數(shù)為1,但這不符合微博字?jǐn)?shù)限制需求,中文必須計(jì)算為2才可以。
google了下,找到一個(gè)discuz中截取各種編碼字符的類,改造了下,已經(jīng)測(cè)試通過(guò).其中參數(shù)$charset 只支持gbk與utf-8。

復(fù)制代碼 代碼如下:

$a = "s@@你好";
var_dump(strlen_weibo($a,'utf-8'));

結(jié)果輸出為8,其中字母s計(jì)數(shù)為1,全角@計(jì)數(shù)為2,半角@計(jì)數(shù)為1,兩個(gè)中文計(jì)數(shù)為4。源碼如下:

復(fù)制代碼 代碼如下:

function strlen_weibo($string, $charset='utf-8')
{
    $n = $count = 0;
    $length = strlen($string);
    if (strtolower($charset) == 'utf-8')
    {
        while ($n < $length)
        {
            $currentByte = ord($string[$n]);
            if ($currentByte == 9 ||
                $currentByte == 10 ||
                (32 <= $currentByte && $currentByte <= 126))
            {
                $n++;
                $count++;
            } elseif (194 <= $currentByte && $currentByte <= 223)
            {
                $n += 2;
                $count += 2;
            } elseif (224 <= $currentByte && $currentByte <= 239)
            {
                $n += 3;
                $count += 2;
            } elseif (240 <= $currentByte && $currentByte <= 247)
            {
                $n += 4;
                $count += 2;
            } elseif (248 <= $currentByte && $currentByte <= 251)
            {
                $n += 5;
                $count += 2;
            } elseif ($currentByte == 252 || $currentByte == 253)
            {
                $n += 6;
                $count += 2;
            } else
            {
                $n++;
                $count++;
            }
            if ($count >= $length)
            {
                break;
            }
        }
        return $count;
    } else
    {
        for ($i = 0; $i < $length; $i++)
        {
            if (ord($string[$i]) > 127)
            {
                $i++;
                $count++;
            }
            $count++;
        }
        return $count;
    }
}

相關(guān)文章

最新評(píng)論