加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-13 22:05:45 所属栏目:百科 来源:网络整理
导读:贪婪匹配:正则表达式一般趋向于最大长度匹配,也就是所谓的贪婪匹配。 非贪婪匹配:就是匹配到结果就好,就少的匹配字符。 那么,我们实用一下 使用php 的行数preg_match_all 以下我们要将字符串content 中的两个链接取出来 ?php$content='a target="_blank"

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

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


那么,我们实用一下

使用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



















网址导航

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读