欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

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

復制代碼 代碼如下:

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

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

復制代碼 代碼如下:

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;
    }
}

相關文章

最新評論