PHP 提供多種字串比較函數,按字節、自然排序、大小寫敏感度、指定長度等不同語義滿足多樣化需求。
| 函數 | 比較方式 | 大小寫敏感 | 特殊特性 | 回傳值 |
|---|---|---|---|---|
strcmp() | 按字節 (ASCII) | 是 | 二進制安全 | <0, =0, >0 |
strcasecmp() | 按字節 | 否 | 忽略大小寫 | <0, =0, >0 |
strnatcmp() | 自然排序 | 是 | 數字按數值比較 | <0, =0, >0 |
strncasecmp() | 自然排序 | 否 | 忽略大小寫 + 自然排序 | <0, =0, >0 |
strncmp() | 指定長度字節 | 是 | 只比前 n 字符 | <0, =0, >0 |
0:兩字串相等(按比較規則)< 0:$str1 小於 $str2> 0:$str1 大於 $str2<?php
$a = "Hello"; $b = "hello";
echo strcmp($a, $b); // -1 (H=72 < h=104)
echo strcasecmp($a, $b); // 0 (忽略大小寫視為相等)
?>
<?php
$files = ['file1.txt', 'file10.txt', 'file2.txt'];
sort($files); // 標準排序:file1, file10, file2
usort($files, 'strnatcmp'); // 自然排序:file1, file2, file10
print_r($files);
?>
<?php
$a = "www.example.com";
$b = "www.example.org";
echo strncmp($a, $b, 11); // 0 (前 11 字符 "www.example" 相同)
echo strncmp($a, $b, 12); // -1 (.com < .org)
?>
<?php
$versions = ['1.2.10', '1.2.3', '1.10.1', '1.2.1'];
usort($versions, 'strnatcmp');
print_r($versions);
// 正確版本號排序:1.2.1, 1.2.3, 1.2.10, 1.10.1
?>
strcmp() 最快===,避免函數呼叫開銷選擇正確的比較函數,能讓排序、去重、查找等邏輯符合業務預期,避免「10 排在 2 前面」這類經典 Bug。