preg_match_all 正则表达式贪婪与非贪婪模式

贪婪匹配:正则表达式一般趋向于最大长度匹配,也就是所谓的贪婪匹配。

非贪婪匹配:就是匹配到结果就好,就少的匹配字符。

 

那么,我们实用一下

使用php 的行数preg_match_all

以下我们要将字符串content 中的两个链接取出来

 

 

<?php
$content='<a target="_blank" href="/videos/68759vod-play-id-68759-sid-0-pid-1.html">BD</a><a target="_blank" href="/videos/68759vod-play-id-68759-sid-0-pid-0.html">DVD</a>b';
$play_pattern = '/<a  target=\"_blank\" href=\"(.*)\">(.*)<\/a>/i';
preg_match_all($play_pattern, $content, $play_list);
print_r($play_list);


我们得到的结果是

Array
(
[0] => Array
(
[0] => <a target="_blank" href="/videos/68759vod-play-id-68759-sid-0-pid-1.html">BD</a><a target="_blank" href="/videos/68759vod-play-id-68759-sid-0-pid-0.html">DVD</a>
)


[1] => Array
(
[0] => /videos/68759vod-play-id-68759-sid-0-pid-1.html">BD</a><a target="_blank" href="/videos/68759vod-play-id-68759-sid-0-pid-0.html
)


[2] => Array
(
[0] => DVD
)


)

 

这显然不是我们想要的。

那么,我么么只要把$play_pattern加多一个字母,就能匹配到我们所需要的信息

 

$play_pattern = '/<a  target=\"_blank\" href=\"(.*)\">(.*)<\/a>/iU';

 

结果就是

Array
(
[0] => Array
(
[0] => <a target="_blank" href="/videos/68759vod-play-id-68759-sid-0-pid-1.html">BD</a>
[1] => <a target="_blank" href="/videos/68759vod-play-id-68759-sid-0-pid-0.html">DVD</a>
)


[1] => Array
(
[0] => /videos/68759vod-play-id-68759-sid-0-pid-1.html
[1] => /videos/68759vod-play-id-68759-sid-0-pid-0.html
)


[2] => Array
(
[0] => BD
[1] => DVD
)


)

 

贪婪模式和非贪婪模式差别就是那么大。

在正则html上的列表的时候,经常就会出现这样的错误。使用preg_match_all正则匹配到了整个字符串,但是子串的匹配被忽略了。导致结果错误。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Yoper

chen.yong.peng@foxmail.com

2016.08.01

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

网址导航

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值