preg_match
int preg_match ( string pattern, string subject [, array matches [, int flags]] )
array matches 是一個數組,matches[0]表示匹配的字符串,matches[1]表示匹配的第一個括號塊得內容,matches[2]表示匹配的第二個括號塊得內容,和perl的正則裏面的$1,$2,$3 類似
<?php
// 從 URL 中取得主機名
preg_match("/^(http:\/\/)?([^\/]+)/i",
"http://www.php.net/index.html", $matches);
$host = $matches[2];
// 從主機名中取得後面兩段
preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches);
echo "domain name is: {$matches[0]}\n";
?>
preg_match_all
int preg_match_all ( string pattern, string subject, array matches [, int flags] )
array matches 是一個數組,matches[0]表示匹配的字符串數組, 爲第一個括號中的子模式所匹配的字符串組成的數組, 爲第二個括號中的子模式所匹配的字符串組成的數組,和perl的正則裏面的$1,$2,$3 類似
<?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";
}
?>