|
微博的發(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'));
結(jié)果輸出為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;
}
}
php技術(shù):php截取字符串之截取utf8或gbk編碼的中英文字符串示例,轉(zhuǎn)載需保留來源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯(lián)系我們修改或刪除,多謝。