preg_matchphp
int preg_match ( string pattern, string subject [, array matches [, int flags]] )html
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] )dom
array matches 是一個數組,matches[0]表示匹配的字符串數組, 爲第一個括號中的子模式所匹配的字符串組成的數組, 爲第二個括號中的子模式所匹配的字符串組成的數組,和perl的正則裏面的$1,$2,$3 相似ide
<?php
spa
// \\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";
}
?>