核心函數比較表
| 函數 | 用途 | 回傳值 | 典型用途 |
preg_match | 執行一次匹配 | int (0/1/false) | 驗證格式、提取第一組 |
preg_match_all | 全域匹配所有 | int (匹配次數) | 提取所有符合項目 |
preg_replace | 搜尋並替換 | 字串/陣列 | 格式化、過濾、模板替換 |
preg_split | 正則分割字串 | 陣列 | 複雜分隔符分割 |
preg_grep | 陣列元素篩選 | 陣列 | 保留符合模式的元素 |
preg_quote | 跳脫正則特殊字元 | 字串 | 動態建構模式時必用 |
preg_last_error | 取得最後錯誤碼 | int | 除錯用 |
preg_match:單次匹配
$pattern = '/(\d{4})-(\d{2})-(\d{2})/';
$str = "今天是 2024-01-15";
if (preg_match($pattern, $str, $matches)) {
echo "完整:{$matches[0]}<br>"; // 2024-01-15
echo "年:{$matches[1]}<br>"; // 2024
echo "月:{$matches[2]}<br>"; // 01
echo "日:{$matches[3]}<br>"; // 15
}
// 命名群組 (PHP 5.2.2+)
$pattern = '/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/';
preg_match($pattern, $str, $matches);
echo $matches['year']; // 2024
preg_match_all:全域匹配
$str = "a1b2c3d4";
preg_match_all('/\d/', $str, $matches);
print_r($matches[0]); // ['1','2','3','4']
// PREG_SET_ORDER 重組結構
preg_match_all('/(\w)(\d)/', $str, $matches, PREG_SET_ORDER);
/*
Array(
[0] => ['a1','a','1'],
[1] => ['b2','b','2'],
...
)
*/
preg_replace:搜尋替換
// 基本替換
echo preg_replace('/\d+/', '*', 'abc123def456'); // abc*def*
// 回參考
echo preg_replace('/(\w)(\d)/', '$2$1', 'a1b2'); // 1a2b
// 陣列批次
echo preg_replace(['/\d/', '/[a-z]/'], ['*', '#'], 'a1b2'); // #*#*
// 限制次數
echo preg_replace('/\d/', '*', '12345', 2); // **345
// e 修飾符 (PHP 7.0 移除,改用 preg_replace_callback)
echo preg_replace_callback('/(\d+)/', fn($m) => $m[1]*2, '3 5 7'); // 6 10 14
preg_split:正則分割
$str = "apple, banana; orange |grape";
// 多種分隔符
$fruits = preg_split('/\s*[,;|]\s*/', $str);
// ['apple','banana','orange','grape']
// 保留分隔符
$parts = preg_split('/(\s+)/', "a b\tc", -1, PREG_SPLIT_DELIM_CAPTURE);
// ['a', ' ', 'b', '\t', 'c']
// 移除空元素
$parts = preg_split('/\s+/', "a b c", -1, PREG_SPLIT_NO_EMPTY);
preg_grep:陣列篩選
$files = ['test.php', 'image.jpg', 'style.css', 'script.js', 'README.md'];
$phpFiles = preg_grep('/\.php$/i', $files);
// ['test.php']
// 反向篩選 (PREG_GREP_INVERT)
$nonPhp = preg_grep('/\.php$/i', $files, PREG_GREP_INVERT);
preg_replace_callback 進階替換
// 模板引擎簡易版
$template = "Hello {name}, your balance is {balance}.";
$data = ['name' => '張三', 'balance' => 12345];
$result = preg_replace_callback('/\{(\w+)\}/', function($m) use ($data) {
return $data[$m[1]] ?? $m[0]; // 找不到保留原樣
}, $template);
echo $result; // Hello 張三, your balance is 12345.
錯誤處理
$result = preg_match('/(?P<invalid/', $str);
if ($result === false) {
$error = preg_last_error();
$messages = [
PREG_INTERNAL_ERROR => '內部錯誤',
PREG_BACKTRACK_LIMIT_ERROR => '回溯限制',
PREG_RECURSION_LIMIT_ERROR => '遞迴限制',
PREG_BAD_UTF8_ERROR => '無效 UTF-8',
PREG_BAD_UTF8_OFFSET_ERROR => 'UTF-8 偏移錯誤',
PREG_JIT_STACKLIMIT_ERROR => 'JIT 堆疊限制',
];
echo "Regex 錯誤: " . ($messages[$error] ?? "未知錯誤 $error");
}