| 模式 | 含義 | 匹配範例 | 結果 (輸入: left:0px;top:202px) |
|---|---|---|---|
/\d+/ | 一或多個連續數字 | 連續數字群組 | [0, 202, 90, 30] |
/\d/ | 單個數字 | 每個數字獨立 | [0, 2, 0, 2, 9, 0, 3, 0] |
/(\d+)/ | 捕獲組:連續數字 | 同 \d+ 但 $matches[1] 為捕獲組 | $matches[1] = [0, 202, 90, 30] |
/\b\d+\b/ | 單字邊界數字 | 獨立數字詞 | 視分隔符而定 |
<?php
$pattern = '/\d+/';
$subject = "left:0px;top:202px;width:90px;height:30px";
$matches = [];
// PREG_PATTERN_ORDER (預設): $matches[0] 完整匹配,$matches[1] 第一捕獲組...
preg_match_all($pattern, $subject, $matches, PREG_PATTERN_ORDER);
// $matches[0] = ['0', '202', '90', '30']
// PREG_SET_ORDER: $matches[0] = [完整匹配, 捕獲1, 捕獲2...]
preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER);
// $matches = [['0'], ['202'], ['90'], ['30']]
// PREG_OFFSET_CAPTURE: 包含偏移位置
preg_match_all($pattern, $subject, $matches, PREG_OFFSET_CAPTURE);
// $matches[0] = [['0', 5], ['202', 10], ['90', 22], ['30', 33]]
?>
<?php
function extractAllNumbers(string $str): array
{
preg_match_all('/\d+/', $str, $matches);
return array_map('intval', $matches[0]);
}
$str = "價格: $1,299.99, 數量: 5, 重量: 1.5kg";
print_r(extractAllNumbers($str));
// [1, 299, 99, 5, 1, 5] 注意: 小數點會被分割
?>
<?php
function extractNumbers(string $str): array
{
// 匹配: 可選負號、數字、可選千分位、可選小數部分
$pattern = '/-?(?:\d{1,3}(?:,\d{3})*|\d+)(?:\.\d+)?/';
preg_match_all($pattern, $str, $matches);
return array_map(fn($v) => (float)str_replace(',', '', $v), $matches[0]);
}
$str = "溫度: -12.5°C, 價格: $1,299.99, 數量: 5, 比率: 3.14159";
print_r(extractNumbers($str));
// [-12.5, 1299.99, 5, 3.14159]
?>
<?php
function extractFixedLengthNumbers(string $str, int $length): array
{
$pattern = '/\b\d{' . $length . '}\b/';
preg_match_all($pattern, $str, $matches);
return $matches[0];
}
$str = "訂單: 20240115, 電話: 0912345678, 身分證: A123456789";
print_r(extractFixedLengthNumbers($str, 8)); // ['20240115']
print_r(extractFixedLengthNumbers($str, 10)); // ['0912345678']
?>
<?php
function getFirstNumber(string $str, int $minLength = 1): ?string
{
$pattern = '/\d{' . $minLength . ',}/';
return preg_match($pattern, $str, $matches) ? $matches[0] : null;
}
function getFirstNumberExactLength(string $str, int $length): ?string
{
$pattern = '/\b\d{' . $length . '}\b/';
return preg_match($pattern, $str, $matches) ? $matches[0] : null;
}
$str = "時代發123生的12345678發生的";
echo getFirstNumber($str); // 123
echo getFirstNumber($str, 4); // 12345678
echo getFirstNumberExactLength($str, 8); // 12345678
?>
<?php
// 移除所有數字
$str = "ABC123DEF456";
echo preg_replace('/\d+/', '', $str); // ABCDEF
// 替換為星號
echo preg_replace('/\d+/', '*', $str); // ABC*DEF*
// 遮罩手機中間四碼
$phone = '0912345678';
echo preg_replace('/(\d{4})\d{4}(\d{2})/', '$1****$2', $phone); // 0912****78
// 格式化數字:每三位加逗號
$num = '1234567890';
echo preg_replace('/(\d)(?=(\d{3})+(?!\d))/', '$1,', $num); // 1,234,567,890
?>
<?php
function extractTaiwanId(string $str): ?string
{
// 格式: 1 個英文字母 + 9 個數字
$pattern = '/[A-Z][0189]\d{8}/i';
return preg_match($pattern, $str, $m) ? $m[0] : null;
}
?>
<?php
function extractTaiwanBan(string $str): ?string
{
// 8 位數字
$pattern = '/\b\d{8}\b/';
return preg_match($pattern, $str, $m) ? $m[0] : null;
}
?>
<?php
function extractPhoneNumbers(string $str, string $region = 'TW'): array
{
$patterns = [
'TW' => '/\b09\d{8}\b/', // 台灣: 09xxxxxxxx
'CN' => '/\b1[3-9]\d{9}\b/', // 中國: 13-19 開頭 11 位
'HK' => '/\b[569]\d{7}\b/', // 香港: 5/6/9 開頭 8 位
'US' => '/\b\d{3}[-. ]?\d{3}[-. ]?\d{4}\b/', // 美國格式
];
$pattern = $patterns[$region] ?? $patterns['TW'];
preg_match_all($pattern, $str, $matches);
return array_unique($matches[0]);
}
?>
<?php
function extractPrices(string $str): array
{
// 匹配: $/NT$/USD 等符號 + 數字 (含千分位、小數)
$pattern = '/(?:NT\$|USD|\$|¥|€|£)\s*-?(?:\d{1,3}(?:,\d{3})*|\d+)(?:\.\d{1,2})?/';
preg_match_all($pattern, $str, $matches);
return $matches[0];
}
$str = "原價 NT$1,299, 特價 $999.99, 歐元 €89.50";
print_r(extractPrices($str));
// ['NT$1,299', '$999.99', '€89.50']
?>
\b 邊界、^$ 錨點、具體前綴.* 易導致回溯災難,改用 [^"]* 等具體字符類preg_match_all,避免記憶體峰值<?php
class NumberExtractor
{
// 靜態快取編譯模式
private static array $patterns = [];
private static function getPattern(string $pattern): string
{
return self::$patterns[$pattern] ??= $pattern;
}
public static function extractAll(string $str): array
{
return self::extractWithPattern($str, '/\d+/');
}
public static function extractWithPattern(string $str, string $pattern): array
{
$compiled = self::getPattern($pattern);
preg_match_all($compiled, $str, $matches);
return $matches[0];
}
}
?>
'/\d+/ ' vs "/\\d+/",單引號不解析變數但需雙重跳脫反斜線/\d.*\d/ 會匹配整行,應用 /\d+?/ 非貪婪或具體模式preg_* 預期 UTF-8,/u 修飾符明確宣告pcre.backtrack_limit (預設 1000000),需調大或優化正則PHP 正則提取數字核心在於:選對模式 (\d+ vs \d)、善用捕獲組、理解 PREG_* 旗標、處理邊界與格式。常用場景封裝為工具函數 (extractAllNumbers, extractPrices, extractPhoneNumbers),複雜業務結合 filter_var()、NumberFormatter 等原生函數更穩健。記住:正則強大但非萬能,簡單切割用 explode()、strtok()、sscanf() 往往更快更清晰。