preg_match_all

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

preg_match_all -- 進行全局正則表達式符合

說明

int preg_match_all ( string pattern, string subject, array matches [, int flags] )

subject 中搜尋所有與 pattern 給出的正則表達式符合的內容並將結果以 flags 特殊的順序放到 matches 中。

搜尋到第一個符合項之後,接下來的搜尋從上一個符合項末尾開始。

flags 可以是下列旗標的組合(注意把 PREG_PATTERN_ORDERPREG_SET_ORDER 合起來用沒有意義):

PREG_PATTERN_ORDER

對結果排序使 $matches[0] 為全部模式符合的陣列,$matches[1] 為第一個括號中的子模式所符合的字串組成的陣列,以此類推。

<?php
preg_match_all 
("|<[^>]+>(.*)</[^>]+>|U",
    
"<b>example: </b><div align=left>this is a test</div>",
    
$outPREG_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>",
    
$outPREG_SET_ORDER);
print 
$out[0][0].", ".$out[0][1]."\n";
print 
$out[1][0].", ".$out[1][1]."\n";
?>

本例將輸出:

<b>example: </b>, example:
<div align=left>this is a test</div>, 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 1-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$icount($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>

參見 preg_match()preg_replace()preg_split()