萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP ctype 函數族完全指南:高效字元分類驗證替代正則

為什麼選擇 ctype?

  • 效能優異:C 層實作,比 PCRE 正則快 5-10 倍
  • 語義清晰:函數名即文檔,ctype_digit() 比 preg_match('/^\d+$/') 更易讀
  • 零依賴:PHP 4.2+ 內建,無需安裝擴展
  • 嚴格模式:僅接受純字串,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 倍
*/

注意事項與限制

  • 空字串:所有 ctype 函數對空字串回傳 false (PHP 5.1+)
  • 整數參數:傳入整數會被視為 ASCII 碼,ctype_digit(123) → 檢查字元 '{' (ASCII 123) → false。務必轉字串:ctype_digit((string)$int)
  • 非字串輸入:PHP 8.1+ 拋出 TypeError,舊版發出警告並回傳 false
  • Locale 影響:ctype_alpha 等受 setlocale(LC_CTYPE) 影響,多語言環境建議明確設定 setlocale(LC_CTYPE, 'C')

總結

ctype 函數族是 PHP 表單驗證、資料清洗的利器:快速、嚴格、語意化。下次寫 preg_match('/^[0-9]+$/') 時,請改用 ctype_digit(),你的 CPU 會感謝你。

copyright © 萬盛學電腦網 all rights reserved