PHP strlen() 字串長度
strlen() 函數用來取得字串的長度(位元組數)。
基本用法
<?php
$str = "Hello";
echo strlen($str); // 5
$str = "Hello World";
echo strlen($str); // 11(包含空格)
$empty = "";
echo strlen($empty); // 0
?>
語法
strlen(string $string): int
$string:要計算長度的字串- 回傳值:字串的位元組數
注意:位元組 vs 字元
strlen() 回傳的是位元組數,不是字元數。對於 ASCII 字元,一個字元等於一個位元組,但對於中文等多位元組字元,一個字元可能佔多個位元組。
<?php
// ASCII 字串
echo strlen("Hello"); // 5
// 中文字串(UTF-8 編碼,一個中文字佔 3 位元組)
echo strlen("你好"); // 6
echo strlen("哈囉世界"); // 12
?>
mb_strlen() - 字元數
如果要取得實際的字元數(適用於中文),使用 mb_strlen():
<?php
$str = "你好世界";
echo strlen($str); // 12(位元組數)
echo mb_strlen($str); // 4(字元數)
// 指定編碼
echo mb_strlen($str, 'UTF-8'); // 4
?>
mb_strlen() 需要啟用 mbstring 擴展。混合字串
<?php
$str = "Hello 你好";
echo strlen($str); // 12 (5 + 1 + 6)
echo mb_strlen($str); // 8 (5 + 1 + 2)
?>
常見應用
驗證字串長度
<?php
function validatePassword(string $password): bool {
$length = strlen($password);
if ($length < 8) {
echo "密碼至少需要 8 個字元\n";
return false;
}
if ($length > 20) {
echo "密碼不能超過 20 個字元\n";
return false;
}
return true;
}
validatePassword("abc"); // 密碼至少需要 8 個字元
validatePassword("password123"); // true
?>
截斷字串
<?php
function truncate(string $text, int $maxLength): string {
if (strlen($text) <= $maxLength) {
return $text;
}
return substr($text, 0, $maxLength) . '...';
}
echo truncate("Hello World", 5); // Hello...
?>
檢查空字串
<?php
$str = "";
// 使用 strlen
if (strlen($str) === 0) {
echo "字串是空的\n";
}
// 更簡潔的方式
if ($str === "") {
echo "字串是空的\n";
}
// 或使用 empty(但會把 "0" 也視為空)
if (empty($str)) {
echo "字串是空的\n";
}
?>
格式化輸出
<?php
function padRight(string $str, int $length, string $char = ' '): string {
$padding = $length - strlen($str);
if ($padding > 0) {
return $str . str_repeat($char, $padding);
}
return $str;
}
echo padRight("Hello", 10, '-'); // Hello-----
?>
與其他函數比較
| 函數 | 說明 | "Hello" | "你好" |
|---|---|---|---|
strlen() | 位元組數 | 5 | 6 |
mb_strlen() | 字元數 | 5 | 2 |
count_chars() | 字元統計 | - | - |
效能考量
strlen() 是非常快速的操作,PHP 內部會儲存字串長度,所以呼叫 strlen() 只是讀取這個值,不會實際遍歷字串。
<?php
// 快速
$str = str_repeat("a", 1000000);
$start = microtime(true);
$len = strlen($str);
$time = microtime(true) - $start;
echo "Time: {$time}s\n"; // 幾乎是瞬間完成
?>
特殊情況
NULL 位元組
<?php
$str = "Hello\0World";
echo strlen($str); // 11(NULL 位元組也算)
?>
二進位資料
<?php
$binary = "\x00\x01\x02\x03";
echo strlen($binary); // 4
?>