preg_match_all

preg_match_all -- 進行全局正則表達式匹配。

基本介紹

  • 中文名:preg_match_all
  • 例子:preg_match_all 
  • 輸出:<div align=left>th
  • 說明:int preg_match_all
說明,例子,

說明

說明
int preg_match_all ( string pattern, string subject, array matches [, int flags] )
在 subject 中搜尋所有與 pattern 給出的正則表達式匹配的內容並將結果以 flags 指定的順序放到 matches 中。
搜尋到第一個匹配項之後,接下來的搜尋從上一個匹配項末尾開始。
flags 可以是下列標記的組合(注意把 PREG_PATTERN_ORDER 和 PREG_SET_ORDER 合起來用沒有意義):
PREG_PATTERN_ORDER
對結果排序使 $matches[0] 為全部模式匹配的數組,$matches[1] 為第一個括弧中的歡祖子模式所匹配的字元串組成的數組,以此類推。(即$matches[0] [0]為全部模式匹配中的每一項,$matches[0] [1]為全部模式匹配中的第二項,$matches[1] [0]為匹配每一個括弧中的第一項,$matches[1] [1]為匹配每一個括弧中的第二項)
<?php
preg_match_all ("|<[^>]+>(.*)</[^>]+>|U",
"<b>example: </b><div align=left>this is a test</div>",
$out, PREG_PATTERN_ORDER);
print $out[0][0].", ".$out[0][1]."\n";
print $out[1][0].", ".$out[1][1]."\n";
?>
本例將輸出:
<b>example: </b>, <div align=left>this is a test</div>
example: , this is a test
因此,$out[0] 包含匹配整個模式的字辨剃您她符串,$out[1] 包含一對 HTML 標記之間的字元串。
PREG_SET_ORDER
對結果排序使 $matches[0] 為第一組匹配項的數組,$matches[1] 為第二組匹配項的數組,以此類推。
<?php
preg_match_all ("|<[^>]+>(.*)</[^>]+>|U",
"<b>example: </b><div align=left>this is a test</div>",
$out, PREG_SET_ORDER);
print $out[0][0].", "趨祖婆歡.$out[1][0]."\n";
print $out[0][1].", ".$out[1][1]."\n";
?>
本例將輸出:
<b>example: </b>,<嚷芝影div align=left>this is a test</div>
example:, this is a test
本例中,$matches[0] 是第一組匹配結果,$matches[0][0] 包含匹配整個模式的文本,$matches[0][1] 包含匹配第一個子模式的文本,以此類推。同樣,$matches[1] 是第二組匹配結果,等等。
PREG_OFFSET_CAPTURE
如果設定本標記,對每個出現腳剃辣的匹配結果也同時返回其附屬的字元串偏移量。注意這改變了返回的數組的值,使其中的每個單元也是一個數組,其中第一項為匹配字元串,第二項欠探罪為其在 subject 中的偏移量。本標記自 PHP 4.3.0 起可用。
如果沒有給出標記,則假定為 PREG_PATTERN_ORDER。
返回整個模式匹配的次數(可能為零),如果出錯返回 FALSE。

例子

例子 1. 從某文本中取得所有的電話號碼
<?php
preg_match_all ("/\(? (\d{3})? \)? (?(1) [\-\s] ) \d{3}-\d{4}/x",
"Call 555-1212 or 9-800-555-1212", $phones);
?>
例子 2. 搜尋匹配的 HTML 標記(greedy)
<?php
// \\2 是一個逆向引用的例子,其在 PCRE 中的含義是
// 必須匹配正則表達式本身中第二組括弧內的內容,本例中
// 就是 ([\w]+)。因為字元串在雙引號中,所以需要
// 多加一個反斜線。
$html = "<b>bold text</b><a href=howdy.html>click me</a>";
preg_match_all ("/(<促民拜([\w]+)[^>]*>)(.*)(<\/\\2>)/", $html, $matches);
for ($i=0; $i< count($matches[0]); $i++) {
echo "matched: ".$matches[0][$i]."\n";
echo "part 1: ".$matches[1][$i]."\n";
echo "part 2: ".$matches[3][$i]."\n";
echo "part 3: ".$matches[4][$i]."\n\n";
}
?>
本例將輸出:
matched: <b>bold text</b>
part 1: <b>
part 2: bold text
part 3: </b>
matched: <a href=howdy.html>click me</a>
part 1: <a href=howdy.html>
part 2: click me
part 3: </a>

相關詞條

熱門詞條

聯絡我們