preg_match_all — 进行全局正则表达式匹配
说明
复制代码 代码如下:
int preg_match_all ( string pattern, string subject, array matches [, int flags] )
在 subject 中搜索所有与 pattern 给出的正则表达式匹配的内容并将结果以 flags 指定的顺序放到 matches 中。
搜索到第一个匹配项之后,接下来的搜索从上一个匹配项末尾开始。
特别注意preg_pattern_order 和preg_set_order
flags 可以是下列标记的组合(注意把 preg_pattern_order 和 preg_set_order 合起来用没有意义):
如果使用preg_pattern_order
对结果排序使 $matches[0] 为全部模式匹配的数组,$matches[1] 为第一个括号中的子模式所匹配的字符串组成的数组,以此类推。(即$matches[0] [0]为全部模式匹配中的每一项,$matches[0] [1]为全部模式匹配中的第二项,$matches[1] [0]为匹配每一个括号中的第一项,$matches[1] [0]为匹配每一个括号中的第二项)
复制代码 代码如下:
(.*)[^>]+>|u,example: this is a test
,$out, preg_pattern_order);
print $out[0][0]., .$out[0][1].\n;
print $out[1][0]., .$out[1][1].\n;
?>
本例将输出:
复制代码 代码如下:
example: , this is a test
example: , this is a test
因此,$out[0] 包含匹配整个模式的字符串,$out[1] 包含一对 html 标记之间的字符串。
如果使用preg_set_order
对结果排序使 $matches[0] 为第一组匹配项的数组,$matches[1] 为第二组匹配项的数组,以此类推。(即$matches[0] [0]为第一组匹配项中完整匹配的字符串,$matches[0] [1]为第一组匹配中完整匹配第一个括号中的字符串)
复制代码 代码如下:
(.*)[^>]+>|u,example: this is a test
,$out, preg_set_order);
print $out[0][0]., .$out[0][1].\n;
print $out[1][0]., .$out[1][1].\n;
?>
本例将输出:
复制代码 代码如下:
example: , example:
this is a test
, this is a test
本例中,$matches[0] 是第一组匹配结果,$matches[0][0] 包含匹配整个模式的文本,$matches[0][1] 包含匹配第一个子模式的文本,以此类推。同样,$matches[1] 是第二组匹配结果,等等。
preg_offset_capture
如果设定本标记,对每个出现的匹配结果也同时返回其附属的字符串偏移量。注意这改变了返回的数组的值,使其中的每个单元也是一个数组,其中第一项为匹配字符串,第二项为其在 subject 中的偏移量。本标记自 php 4.3.0 起可用。
如果没有给出标记,则假定为 preg_pattern_order。
返回整个模式匹配的次数(可能为零),如果出错返回 false。
例子 1. 从某文本中取得所有的电话号码
复制代码 代码如下:
例子 2. 搜索匹配的 html 标记(greedy)
复制代码 代码如下:
)(.*)()/, $html, $matches);
for ($i=0; $iecho 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;
}
?>
本例将输出:
复制代码 代码如下:
matched: bold text
part 1:
part 2: bold text
part 3:
matched: click me
part 1:
part 2: click me
part 3:
http://www.bkjia.com/phpjc/728085.htmlwww.bkjia.comtruehttp://www.bkjia.com/phpjc/728085.htmltecharticlepreg_match_all — 进行全局正则表达式匹配 说明 复制代码 代码如下: int preg_match_all ( string pattern, string subject, array matches [, int flags] ) 在 subjec...