| 模式 | 說明 |
|---|---|
^ | 字串開頭 (多行模式下為行首) |
$ | 字串結尾 (多行模式下為行尾) |
\s | 空白字元 (空格、Tab、換行、換頁) |
\d | 數字 [0-9] |
\w | 單字字元 [a-zA-Z0-9_] |
. | 任意字元 (除換行,含 s 修飾符則含換行) |
/^\s*|\s*$/ // 替換為空字串即可 trim
/^[\x{4e00}-\x{9fa5}a-zA-Z0-9_]+$/u
u 修飾符啟用 Unicode 支援,\x{4e00}-\x{9fa5} 涵蓋 CJK 統一表意文字基本區。
/^[".chr(0xa1)."-".chr(0xff)."a-zA-Z0-9_]+$/
/[a-zA-Z]+:\/\/[^\s]*/
/^[a-zA-Z][a-zA-Z0-9_]{4,15}$/
/\d{3}-\d{8}|\d{4}-\d{7}/
匹配 02-12345678、0511-12345678 等。
/^[1-9]\d{4,10}$/
/^[1-9]\d{5}(?!\d)/
(?!\d) 否定前瞻確保不超過 6 位。
/^\d{15}$|^\d{17}[\dXx]$/
18 位末碼可為 X/x (檢查碼)。注意:此僅檢查格式,真實性需加權校驗演算法。
/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/
嚴格版 (各段 0-255):
/^((25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(25[0-5]|2[0-4]\d|[01]?\d?\d)$/
<?php
class Validator {
private array $patterns = [
'username' => '/^[a-zA-Z][a-zA-Z0-9_]{4,15}$/',
'email' => '/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/',
'mobile' => '/^1[3-9]\d{9}$/', // 中國大陸手機
'idcard' => '/^\d{17}[\dXx]$/',
'zip' => '/^[1-9]\d{5}$/',
'ipv4' => '/^((25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(25[0-5]|2[0-4]\d|[01]?\d?\d)$/',
'url' => '/^https?:\/\/[^\s]+$/i',
'zh_en_num' => '/^[\x{4e00}-\x{9fa5}a-zA-Z0-9_]+$/u',
];
public function check(string $field, string $value): bool {
return isset($this->patterns[$field])
&& preg_match($this->patterns[$field], $value) === 1;
}
public function addPattern(string $name, string $pattern): self {
$this->patterns[$name] = $pattern;
return $this;
}
}
// 使用
$v = new Validator();
if (!$v->check('username', $_POST['user'])) {
exit('帳號格式錯誤');
}
?>
^ 讓引擎快速失敗。(.*)*,改用佔有優先量詞 .*+ 或原子群組 (?>...)。preg_last_error() 檢查錯誤代碼。