ctype_digit() 比 preg_match('/^\d+$/') 更易讀123.45、-10、' 123 ' 皆回傳 false| 函數 | 檢測內容 | 等效正則 | 通過範例 | 失敗範例 |
|---|---|---|---|---|
ctype_alnum | 英數字 | /^[A-Za-z0-9]+$/ | 'Abc123' | 'Abc-123', '中文' |
ctype_alpha | 純字母 | /^[A-Za-z]+$/ | 'Hello' | 'Hello1', 'Hello!' |
ctype_cntrl | 控制字元 | /^[\x00-\x1F\x7F]+$/ | "\n\r\t" | 'a', '1', ' ' |
ctype_digit | 純數字 0-9 | /^[0-9]+$/ | '12345' | '-1', '1.2', '0x10' |
ctype_graph | 可列印非空白 | /^[\x21-\x7E]+$/ | 'Hello!', 'A1#' | 'Hello ', "\n" |
ctype_lower | 純小寫字母 | /^[a-z]+$/ | 'hello' | 'Hello', 'hello1' |
ctype_print | 可列印含空白 | /^[\x20-\x7E]+$/ | 'Hello World' | "\n", "\t" |
ctype_punct | 標點符號 | /^[\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]+$/ | '!@#$%' | 'a', '1', ' ' |
ctype_space | 空白字元 | /^[\s]+$/ | " \t\n\r" | 'a', '1', '' |
ctype_upper | 純大寫字母 | /^[A-Z]+$/ | 'HELLO' | 'Hello', 'HELLO1' |
ctype_xdigit | 十六進位字元 | /^[0-9A-Fa-f]+$/ | 'ABCDEF123456' | 'GHI', '123xyz' |
<?php
$str = '0.1123';
// ctype_digit: 嚴格純數字
var_dump(ctype_digit($str)); // bool(false) - 含小數點
// is_numeric: 寬鬆數值判斷
var_dump(is_numeric($str)); // bool(true) - 認為是數值
// 實務差異:表單驗證年齡
$age = $_POST['age'] ?? '';
if (ctype_digit($age)) { // 嚴格:必須是 '18'、'25'
$ageInt = (int)$age;
} else {
// 拒絕 '18.5', '-1', ' 18 ', '1e2'
}
<?php
class Validator {
public static function username(string $v): bool {
// 3-20 位英數字、底線、連字號
return strlen($v) >= 3 && strlen($v) <= 20 && ctype_alnum(str_replace(['-', '_'], '', $v));
}
public static function password(string $v): bool {
// 8-72 位,至少一大一小一數字
if (strlen($v) < 8 || strlen($v) > 72) return false;
$hasUpper = false; $hasLower = false; $hasDigit = false;
for ($i = 0; $i < strlen($v); $i++) {
$ch = $v[$i];
if (ctype_upper($ch)) $hasUpper = true;
elseif (ctype_lower($ch)) $hasLower = true;
elseif (ctype_digit($ch)) $hasDigit = true;
}
return $hasUpper && $hasLower && $hasDigit;
}
public static function hexColor(string $v): bool {
// #RRGGBB 或 #RGB
if ($v[0] !== '#') return false;
$hex = substr($v, 1);
return (strlen($hex) === 3 || strlen($hex) === 6) && ctype_xdigit($hex);
}
public static function noControlChars(string $v): bool {
// 禁止控制字元 (防止日誌注入等)
for ($i = 0; $i < strlen($v); $i++) {
if (ctype_cntrl($v[$i])) return false;
}
return true;
}
}
// 使用
$rules = [
'username' => ['Username', 'username'],
'password' => ['Password', 'password'],
'color' => ['Hex Color', 'hexColor'],
];
foreach ($rules as $field => [$label, $method]) {
$value = $_POST[$field] ?? '';
if (!Validator::$method($value)) {
echo "$label 格式錯誤\n";
}
}
<?php
$test = str_repeat('a', 1000) . '1'; // 非純字母
$iterations = 100000;
$start = microtime(true);
for ($i = 0; $i < $iterations; $i++) ctype_alpha($test);
echo "ctype_alpha: " . (microtime(true) - $start) . "s\n";
$start = microtime(true);
for ($i = 0; $i < $iterations; $i++) preg_match('/^[A-Za-z]+$/', $test);
echo "preg_match: " . (microtime(true) - $start) . "s\n";
/* 典型輸出:
ctype_alpha: 0.012s
preg_match: 0.089s
→ ctype 快約 7 倍
*/
false (PHP 5.1+)ctype_digit(123) → 檢查字元 '{' (ASCII 123) → false。務必轉字串:ctype_digit((string)$int)TypeError,舊版發出警告並回傳 falsectype_alpha 等受 setlocale(LC_CTYPE) 影響,多語言環境建議明確設定 setlocale(LC_CTYPE, 'C')ctype 函數族是 PHP 表單驗證、資料清洗的利器:快速、嚴格、語意化。下次寫 preg_match('/^[0-9]+$/') 時,請改用 ctype_digit(),你的 CPU 會感謝你。