PHP 程式設計/正則表示式
外觀
< PHP 程式設計
| 字元 | 型別 | 解釋 |
|---|---|---|
| . | 點 | 任何字元 |
| [...] | 方括號 | 字元類: 類中所有列舉的字元 |
| [^...] | 方括號和插入符 | 補充類: 除列舉的字元以外的所有字元 |
| ^ | 插入符 | 字串或行開頭 |
| $ | 美元符號 | 字串或行結尾 |
| | | 管道符 | 備選 |
| (...) | 圓括號 | 捕獲組: 也用於限制備選範圍 |
| * | 星號 | 0、1 或多個出現 |
| + | 加號 | 1 或多個出現 |
| ? | 問號 | 0 或 1 個出現 |
| 類 | 含義 |
|---|---|
| [[:alpha:]] | 任何字母 |
| [[:digit:]] | 任何數字 |
| [[:xdigit:]] | 十六進位制字元 |
| [[:alnum:]] | 任何字母或數字 |
| [[:space:]] | 任何空白字元 |
| [[:punct:]] | 任何標點符號 |
| [[:lower:]] | 任何小寫字母 |
| [[:upper:]] | 任何大寫字母 |
| [[:blank:]] | 空格或製表符 |
| [[:graph:]] | 可顯示和可列印的字元 |
| [[:cntrl:]] | 跳脫字元 |
| [[:print:]] | 可列印字元,除了控制字元 |
| 表示式 | 含義 |
|---|---|
| \A | 字串開頭 |
| \b | 單詞字元的開頭或結尾 |
| \d | 數字 |
| \D | 非數字 |
| \s | 空格字元 |
| \S | 非空格字元 |
| \w | 字母、數字或下劃線 |
| \W | 非字母、數字或下劃線字元 |
| \X | Unicode 字元 |
| \z | 字串結尾 |
?:: 在編號時忽略捕獲組。例如:((?:ignored_substring|other).)?!: 否定。例如:((?!excluded_substring).)$1: 第一個捕獲組的結果。
注意: 要搜尋美元符號,"\$" 不起作用,因為這是變數格式,因此必須使用單引號而不是雙引號: '\$'。
在 PHP 中,正則表示式模式必須始終用分隔符包圍。我們通常使用重音符 (`),但也發現 / 和 #。
此外,我們可以在這些分隔符之後新增一些選項
| i | 不區分大小寫 |
| m | `.` 包含回車符 |
| x | 忽略空格 |
| o | 只處理第一個匹配 |
| u | 計算 Unicode 字元(在多位元組中) |
自 PHP 5.3 起,允許在正則表示式中搜索的 ereg() 函式已被 preg_match() 替換。
preg_match[3] 函式是主要的正則表示式搜尋函式[4]。它返回一個布林值,並要求兩個必填引數:正則表示式模式和要掃描的字串。
第三個引數表示儲存結果陣列的變數。
最後,第四個引數接受一個 PHP 標誌,允許修改函式的基本行為。
- 最小示例
<?php
$string = 'PHP regex test for the English Wikibooks.';
if (preg_match('`.*Wikibooks.*`', $string)) {
print('This texts talks about Wikibooks');
} else {
print('This texts doesn\'t talk about Wikibooks');
}
?>
- 高階示例
<?php
$string = 'PHP regex test for the English Wikibooks.';
if (preg_match('`.*Wikibooks.*`', $string), results, $flag) {
var_dump(results);
} else {
print('This texts doesn\'t talk about Wikibooks');
}
?>
標誌示例:[5]
- PREG_OFFSET_CAPTURE: 顯示搜尋子字串在字串中的位置。
- PREG_GREP_INVERT: 在
preg_grep()中顯示反向結果。
此函式在陣列中搜索[6]。
要在一個數組中獲取所有真值結果,請將 preg_match 替換為 preg_match_all[7],並將 print 替換為 print_r。
篩選檔案內容的示例
$regex = "/\(([^)]*)\)/";
preg_match_all($regex, file_get_contents($filename), $matches);
print_r($matches);
preg_replace 函式接受三個引數:要替換和要替換的字串。
<?php
// Replace spaces by underscores
$string = "PHP regex test for the English Wikibooks.";
$sortedString = preg_replace('`( )`', '_', $string);
echo $sortedString;
?>
與 preg_replace() 相同,但其結果只包含替換。
分解字串。
- ↑ https://www.regular-expressions.info/posixbrackets.html
- ↑ http://www.regular-expressions.info/unicode.html
- ↑ https://php.net.tw/manual/en/function.preg-match.php
- ↑ https://php.net.tw/manual/en/ref.pcre.php
- ↑ https://php.net.tw/manual/en/pcre.constants.php
- ↑ https://php.net.tw/manual/fr/function.preg-grep.php
- ↑ http://www.expreg.com/pregmatchall.php