php截取字串之截取utf8或gbk編碼的中英文字串樣本_PHP教程

來源:互聯網
上載者:User
微博的發言有字數限制,其計數方式是,中文算2個,英文算1個,全形字元算2個,半形字元算1個。
php中內建strlen是返回的位元組數,對於utf8編碼的中文返回時3個,不滿足需求。
mb_strlen 可以根據字元集計算長度,比如utf8的中文計數為1,但這不符合微博字數限制需求,中文必須計算為2才可以。
google了下,找到一個discuz中截取各種編碼字元的類,改造了下,已經測試通過.其中參數$charset 只支援gbk與utf-8。

複製代碼 代碼如下:
$a = "s@@你好";
var_dump(strlen_weibo($a,'utf-8'));

結果輸出為8,其中字母s計數為1,全形@計數為2,半形@計數為1,兩個中文計數為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;
}
}

http://www.bkjia.com/PHPjc/740663.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/740663.htmlTechArticle微博的發言有字數限制,其計數方式是,中文算2個,英文算1個,全形字元算2個,半形字元算1個。 php中內建strlen是返回的位元組數,對於u...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.