preg_match and preg_match_all

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

 

你可能感兴趣的:(PHP,职场,休闲,preg_match,preg_match_all)