php正则preg,php正则函数2preg_match_all

php正则函数二preg_match_all

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

? ? ? ? 函数原型:

?

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直至结尾,有几个匹配结果就返回几。看个有匹配结果的例子。

?

$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[0]存放匹配的结果,$matches[1]存放子正则1匹配的结果,$matches[2]存放正则2匹配的结果。可能说的不太直观,看下图就明白了

?

174658585.jpg

黑色箭头是$pattern正则匹配,绿箭头是子正则匹配。

再看个未匹配成功的例子

$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

?

本条技术文章来源于互联网,如果无意侵犯您的权益请点击此处反馈版权投诉

本文系统来源:php中文网

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值