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

来源:互联网 发布:一斩必杀·村雨淘宝 编辑:程序博客网 时间:2024/05/17 22:38

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

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


那么,我们实用一下

使用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
原创粉丝点击