Home > Backend Development > PHP Tutorial > php正则函数2preg_match_all

php正则函数2preg_match_all

WBOY
Release: 2016-06-13 12:50:47
Original
752 people have browsed it

php正则函数二preg_match_all

? ? ? ? 继续来说perl风格的正则函数preg_match_all。

? ? ? ? 函数原型:

?

<?php>
preg_match_all ($pattern, $subject, array &$matches = null, $flags = null, $offset = null)
<?>
Copy after login

?

? ? ? ? 参数:完全和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);
<?>
Copy after login

?输出

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)
Copy after login

?这个例子匹配到两个结果,分别是http://www.sina.com.cn/abc/de/fg.php?fff.html?id=1字符串中红色的两部分。大家会发现$matches中的元素也是数组类型,$matches[0]存放匹配的结果,$matches[1]存放子正则1匹配的结果,$matches[2]存放正则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);
<?>
Copy after login

?输出

int 0

array (size=3)
  0 => 
    array (size=0)
      empty
  1 => 
    array (size=0)
      empty
  2 => 
    array (size=0)
      empty
Copy after login

?

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template