這篇文章主要介紹“php怎么截取utf8或gbk編碼的中英文字符串”,在日常操作中,相信很多人在php怎么截取utf8或gbk編碼的中英文字符串問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”php怎么截取utf8或gbk編碼的中英文字符串”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
微博的發(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; } }
到此,關于“php怎么截取utf8或gbk編碼的中英文字符串”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關知識,請繼續(xù)關注創(chuàng)新互聯(lián)網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>
本文名稱:php怎么截取utf8或gbk編碼的中英文字符串-創(chuàng)新互聯(lián)
文章起源:http://weahome.cn/article/diigeh.html