萬盛學電腦網

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

PHP 純數字驗證:正則表達式與 ctype_digit 效能比較

前言

驗證字串是否為「純數字」是常見需求(如手機號、身分證、數量輸入)。PHP 提供 ctype_digit()、is_numeric()、正則表達式三種方式,本文比較其差異與適用場景。

三種方法比較

方法語法通過範例不通過範例備註
ctype_digit()ctype_digit($str)'123', '0''-123', '12.3', ' 123 ', 123 (int)僅接受 字串且每字元皆為 0-9
is_numeric()is_numeric($val)'123', '-12.5', 123 (int), '0xFF''12a', ''接受整數、浮點數、十六進位、科學標記法;接受純量與字串
正則 /^\d+$/preg_match('/^\d+$/', $str)'123', '0''-123', '12.3', ' 123 '需字串輸入;可擴展長度限制 /^\d{6,10}$/

程式碼範例與效能測試

<?php
function isAllDigitsCtype(string $str): bool
{
    return ctype_digit($str);
}

function isAllDigitsRegex(string $str): bool
{
    return (bool) preg_match('/^\d+$/', $str);
}

function isAllDigitsRegexLen(string $str, int $min, int $max): bool
{
    return (bool) preg_match("/^\\d{$min,$max}$/", $str);
}

// 效能測試 100 萬次
$testStr = '1234567890';
$iterations = 1_000_000;

$start = hrtime(true);
for ($i = 0; $i < $iterations; $i++) {
    ctype_digit($testStr);
}
echo "ctype_digit: " . (hrtime(true) - $start) / 1e6 . " ms" . PHP_EOL;

$start = hrtime(true);
for ($i = 0; $i < $iterations; $i++) {
    preg_match('/^\d+$/', $testStr);
}
echo "preg_match: " . (hrtime(true) - $start) / 1e6 . " ms" . PHP_EOL;

// 典型輸出(PHP 8.2, x64):
// ctype_digit: ~45 ms
// preg_match:  ~120 ms
?>

實務建議

  1. 純數字字串、無長度限制:用 ctype_digit(),最快且語意明確。
  2. 需限定長度範圍:用正則 /^\d{6,10}$/ 或 ctype_digit($str) && strlen($str) >= 6 && strlen($str) <= 10。
  3. 接受整數型別輸入:先 (string)$val 轉字串再用 ctype_digit(),或直接用 is_int($val) && $val >= 0。
  4. 避免 is_numeric() 用於「純數字」檢查:它會通過 '-12.5'、'0xFF' 等非預期格式。

常見陷阱

<?php
// ❌ 錯誤:整數直接傳給 ctype_digit 會警告並回傳 false
ctype_digit(123); // Warning: ctype_digit() expects parameter 1 to be string

// ✅ 正確:轉字串
ctype_digit((string)123); // true

// ❌ 錯誤:包含空白
ctype_digit(' 123 '); // false

// ✅ 正確:先 trim
ctype_digit(trim(' 123 ')); // true
?>

擴展:驗證正整數(含 0)

<?php
function isPositiveInteger(mixed $val): bool
{
    // 接受字串 '0'、'123' 或整數 0、123
    if (is_int($val)) {
        return $val >= 0;
    }
    if (is_string($val)) {
        return ctype_digit($val); // '0' 通過
    }
    return false;
}
?>

總結

驗證「純數字字串」首選 ctype_digit(),效能最佳且語意精確;需長度限制時搭配 strlen() 或改用正則。切勿混淆 is_numeric()(接受浮點、負號、十六進位)與「純數字」的定義。

copyright © 萬盛學電腦網 all rights reserved