php正则函数二preg_match_all
继续来说perl风格的正则函数preg_match_all。函数原型:
<?php
preg_match_all ($pattern, $subject, array &$matches = null, $flags = null, $offset = null)
?>
参数:完全和preg_match一样。
函数功能:类似preg_match,在$subject字符串中匹配$pattern;跟preg_match不同的是,preg_match_all在匹配的第一个结果时不会停止搜索,一直搜索到$subject的结尾。
返回值:根据函数功能就会看出不仅仅返回0或1,preg_match_all会搜索整个$subject直至结尾,有几个匹配结果就返回几。看个有匹配结果的例子。
<?php
$url = 'http://www.sina.com.cn/abc/de/fg.php?fff.html?id=1';
$matches = array();
$pattern = '/(\.){1}[^.|?]+(\?){1}/i';
$count = preg_match_all($pattern, $url, $matches);
var_dump($count);
var_dump($matches);
?>
输出
int 2
array (size=3)
0 =>
array (size=2)
0 => string '.php?' (length=5)
1 => string '.html?' (length=6)
1 =>
array (size=2)
0 => string '.' (length=1)
1 => string '.' (length=1)
2 =>
array (size=2)
0 => string '?' (length=1)
1 => string '?' (length=1)
这个例子匹配到两个结果,分别是http://www.sina.com.cn/abc/de/fg.php?fff.html?id=1字符串中红色的两部分。大家会发现$matches中的元素也是数组类型,$matches存放匹配的结果,$matches存放子正则1匹配的结果,$matches存放正则2匹配的结果。可能说的不太直观,看下图就明白了
黑色箭头是$pattern正则匹配,绿箭头是子正则匹配。
再看个未匹配成功的例子
<?php
$url = 'http://www.sina.com.cn/abc/de/fg.php?fff.html?id=1';
$matches = array();
$pattern = '/(\.){1}[^.|?]+(\?){2}/i';
$count = preg_match_all($pattern, $url, $matches);
var_dump($count);
var_dump($matches);
?>
输出
int 0
array (size=3)
0 =>
array (size=0)
empty
1 =>
array (size=0)
empty
2 =>
array (size=0)
empty
页:
[1]