PHP 提供兩套正則函數:preg_*(PCRE,Perl 兼容)與 ereg_*(POSIX)。POSIX 自 PHP 5.3 棄用,PHP 6 移除,本文專注 PCRE。
模式以雙斜線包裹:/pattern/。
| 元字符 | 說明 | 示例 |
|---|---|---|
| \A | 字符串開頭 | |
| \Z | 字符串結尾 | |
| \b | 單詞邊界 | /\bis/ 匹配以 is 開頭 |
| \B | 非單詞邊界 | /\Bis/ 匹配 This 中的 is |
| \d | 數字 [0-9] | |
| \D | 非數字 [^0-9] | |
| \w | 字母數字下劃線 | |
| \W | 非 \w | |
| \s | 空白字符 | [\f\t\n\r] |
| \S | 非空白 |
i:忽略大小寫m:多行模式s:單行模式(. 匹配換行)x:忽略模式空白U:非貪婪匹配(最近優先)e:替換字符串作為代碼執行(慎用)示例:/apple/i 匹配 apple、Apple、APPLE。
/^\d{2}([\/\-\s])\d{2}\1\d{4}$/
// 匹配 12-31-2006、09/27/1996、86 01 4321
// \1 引用第一個捕獲組的分隔符,保證前後一致
非捕獲組 (?:...) 不佔用引用編號:
/(?:a|b|c)(D|E|F)\1g/ // 匹配 aEEg,\1 引用第二組
preg_match() / preg_match_all()preg_quote()preg_split()preg_grep()preg_replace()preg_match_all('/\s+action=["\'](?!http:)(.*?)["\']\s*/s', $str, $match);
function callback_replace() {
$url = 'https://esfang.house.sina.com.cn';
$str = '...';
$str = preg_replace('/(?<=\saction=["\'])(?!http:)(.*?)(?=["\']\s)/e', "search('$url', '$1')", $str);
echo $str;
}
function search($url, $match) { return $url . '/' . $match; }
preg_match_all('/(?<=<(\w{1})>).*(?=<\/\1>)/', $str, $match);
$form_html = preg_replace('/(?<=\s(action|src|href)=["\'])(?!http:|javascript)(.*?)(?=["\']\s)/e', "add_url('$url', '$1')", $form_html);
正則功能強大但編寫調試耗時,簡單字符串切割(explode、strpos)往往效率更高、可讀性更好。根據任務複雜度選擇工具。