PHP Conference Japan 2024

iconv_strlen

(PHP 5, PHP 7, PHP 8)

iconv_strlen傳回字串的字元數

說明

iconv_strlen(字串 $string, ?字串 $encoding = null): 整數|false

strlen() 不同,iconv_strlen() 會根據指定的字元集計算給定位元組序列 string 中字元的出現次數,其結果不一定與字串的位元組長度相同。

參數

string

字串。

encoding

如果省略 encoding 參數或為 null,則會假設 stringiconv.internal_encoding 編碼。

回傳值

回傳 string 的字元數,為整數;如果編碼過程中發生錯誤,則回傳 false

更新日誌

版本 說明
8.0.0 encoding 現在可以為 null。

參見

新增註記

使用者貢獻的註記 2 則註記

hfuecks @ nospam org
18 年前
如果傳遞給 iconv_strlen 的 UTF-8 字串包含格式錯誤的序列,它將回傳 FALSE。這與 mb_strlen 或 utf8_decode 的行為形成對比,後者會去除任何錯誤的序列;

<?php
# 包含錯誤序列的 UTF-8 字串: \xe9
$str = "I?t?rn?ti?n\xe9?liz?ti?n";

print
"mb_strlen: ".mb_strlen($str,'UTF-8')."\n";
print
"strlen/utf8_decode: ".strlen(utf8_decode($str))."\n";
print
"iconv_strlen: ".iconv_strlen($str,'UTF-8')."\n";
?>

顯示:

mb_strlen: 20
strlen/utf8_decode: 20
iconv_strlen

(PHP 5.0.5)

因此,它比 mb_strlen 更「嚴格」,這可能意味著您需要先檢查無效序列。一種快速檢查的方法是利用 PCRE 擴充功能的行為(請參閱模式修飾符的註記);

<?php
if (preg_match('/^.{1}/us',$str,$ar) != 1) {
die(
"字串包含無效的 UTF-8");
}
?>

可以在以下網址找到較慢但更嚴格的檢查(正規表示式):http://www.w3.org/International/questions/qa-forms-utf-8

類似地,這也適用於 iconv_substr、iconv_strpos 和 iconv_strrpos
sheryl
4 年前
注意到這裡有個斷點
>如果省略 charset 參數,則假設 str 以 iconv.internal_encoding 編碼。

但是點擊 iconv.internal_encoding 連結 (https://php.dev.org.tw/manual/en/iconv.configuration.php),文件指出 iconv.internal_encoding 自 5.6 版起已被棄用。
To Top