preg_match和preg_match_all的区别

来源:互联网 发布:python utf 8 编辑:程序博客网 时间:2024/04/29 10:37

preg_match只匹配一次,preg_match_all是全文匹配


preg_match 字符串比对解析。

语法: int preg_match(string pattern, string subject, array [matches]);

返回值: 整数/数组

函数种类: 资料处理

内容说明: 本函数以 pattern 的规则来解析比对字符串 subject。比对结果返回的值放在数组参数 matches 之中,matches[0] 内容就是原字符串 subject、matches[1] 为第一个合乎规则的字符串、matches[2] 就是第二个合乎规则的字符串,余类推。若省略参数 matches,则只是单纯地比对,找到则返回值为 true。


 

preg_match_all -- 进行全局正则表达式匹配

说明

int preg_match_all ( string pattern, string subject, array matches [, int flags])

subject 中搜索所有与 pattern 给出的正则表达式匹配的内容并将结果以 flags 指定的顺序放到 matches 中。

搜索到第一个匹配项之后,接下来的搜索从上一个匹配项末尾开始。

flags 可以是下列标记的组合(注意把 PREG_PATTERN_ORDERPREG_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>example: , this is a test

因此,$out[0] 包含匹配整个模式的字符串,$out[1] 包含一对 HTML 标记之间的字符串。

原创粉丝点击