php的正则处理函数总结分析

2019-04-10 19:34:46于海丽


提示: 如果只想查看一个字符串是否包含在另一个字符串中,不要用 preg_match()。可以用 strpos() 或 strstr() 替代,要快得多。 

上面是手册里对preg_match()的说明,我认为这个函数的功用在于他可做来做验证,也就是某字符串是否符合某特定要求。其局限是上面所说的要么匹配0次,要么1次。并且返回值是匹配次数。当需要全匹配时可使用preg_match_all().另外值得一提的是$matches数组的作用,可做自模式的返回值,有时很有用。

例:

<?

if (preg_match ("/(bwebb)s(d)/i", "PHP is the web 45 scripting web 34 language of choice.",$match)) {
     print "A match was found.";
print_r($match);
} else {
     print "A match was not found.";
}

?>

<?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
(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_ORDER 和 PREG_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>",
     $out, PREG_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>
相关文章 大家在看