為什麼用 ctype?
- 速度極快: C 底層實作,比 PCRE 正則快 10-50 倍。
- 語意清晰: 函數名即文檔,無需解讀正則語法。
- 無編譯開銷: 不需編譯 Pattern,直接逐字元檢查。
- 適用場景: 純 ASCII 字元分類驗證 (帳號、純數字、十六進位等)。
限制: 僅支援單位元組編碼 (ASCII/ISO-8859-1),不支援 UTF-8 中文。中文驗證請用 preg_match('/^[\x{4e00}-\x{9fa5}]+$/u', $str)。
12 個 ctype 函數完整對照表
| 函數 | 檢查條件 (全字串符合) | 等價正則 (ASCII) | 回傳值 |
ctype_alnum($s) | 英數字 A-Za-z0-9 | /^[A-Za-z0-9]+$/ | bool |
ctype_alpha($s) | 純字母 A-Za-z | /^[A-Za-z]+$/ | bool |
ctype_cntrl($s) | 控制字元 [\x00-\x1F\x7F] | /^[\x00-\x1F\x7F]+$/ | bool |
ctype_digit($s) | 純數字 0-9 | /^[0-9]+$/ | bool |
ctype_graph($s) | 可列印且非空白 [\x21-\x7E] | /^[\x21-\x7E]+$/ | bool |
ctype_lower($s) | 純小寫字母 | /^[a-z]+$/ | bool |
ctype_print($s) | 可列印字元 (含空白) | /^[\x20-\x7E]+$/ | bool |
ctype_punct($s) | 標點符號 (非字數、非空白) | /^[\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]+$/ | bool |
ctype_space($s) | 空白字元 [\s] | /^\s+$/ | bool |
ctype_upper($s) | 純大寫字母 | /^[A-Z]+$/ | bool |
ctype_xdigit($s) | 十六進位 0-9A-Fa-f | /^[0-9A-Fa-f]+$/ | bool |
實戰範例
<?php
// 1. 驗證純數字 ID (比 is_numeric 更嚴格,拒絕 "123.45", "1e5")
if (ctype_digit($_GET['id'] ?? '')) {
$id = (int)$_GET['id'];
}
// 2. 十六進位顏色代碼驗證 (不含 #)
if (ctype_xdigit($color) && strlen($color) === 6) {
// 有效色碼
}
// 3. 帳號只能英數底線 (需額外檢查底線)
if (ctype_alnum(str_replace('_', '', $username)) && !preg_match('/[^a-zA-Z0-9_]/', $username)) {
// 有效帳號
}
// 4. 密碼複雜度:至少一大寫、一小寫、一數字、一標點
$pwd = $_POST['pwd'] ?? '';
$hasUpper = (bool)preg_match('/[A-Z]/', $pwd);
$hasLower = (bool)preg_match('/[a-z]/', $pwd);
$hasDigit = (bool)preg_match('/\d/', $pwd);
$hasPunct = (bool)preg_match('/[!@#$%^&*]/', $pwd);
// ctype 適合「全字串同類」檢查,混合規則仍需正則
// 5. 快速檢查是否全空白
if (ctype_space($input)) { /* 視為空 */ }
// 6. 過濾控制字元 (防注入)
$clean = '';
for ($i = 0, $len = strlen($raw); $i < $len; $i++) {
if (!ctype_cntrl($raw[$i])) $clean .= $raw[$i];
}
?>
效能基準測試參考 (PHP 8.2, 100萬次迴圈)
| 檢查項目 | ctype 函數 | preg_match | 速度比 |
| 純數字 | ctype_digit | /^\d+$/ | ~25x 快 |
| 英數字 | ctype_alnum | /^[a-z\d]+$/i | ~30x 快 |
| 十六進位 | ctype_xdigit | /^[0-9a-f]+$/i | ~20x 快 |
最佳實務建議
- 優先使用 ctype 進行單一字元類別的「全字串」驗證。
- 組合使用:
ctype_digit($age) && $age > 0 && $age < 150。
- 注意空字串: 所有 ctype 函數對空字串回傳
false (PHP 5.1+),符合直覺。
- 整數輸入: 先
ctype_digit 再 (int),避免 is_numeric('1e3') 通過。
- UTF-8 環境: 僅用於 ASCII 欄位 (ID、Token、Hash、色碼),中文欄位改用
mb_check_encoding + 正則。