preg_match and preg_match_all

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

 

 
spa

<?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";
}
?>