【问题标题】:How to get only links with preg_match如何仅获取带有 preg_match 的链接
【发布时间】:2014-01-07 10:06:20
【问题描述】:

来源

<div class=filmPoster-1><a class="fImg1 entityPoster" href="/Zielona.Mila" title="Zielona mila (1999)"> bla bla bla bla
<div class=filmPoster-1><a class="fImg1 entityPoster" href="/Batman" title="Batman (1999)">

如何使用 preg_match 仅获取“/Zielona.Mila,/Batman”(此链接)??

【问题讨论】:

    标签: url preg-match preg-match-all


    【解决方案1】:

    DOM方式(更合适):

    $dom = new DOMDocument();
    @$dom->loadHTML($html);
    $xpath = new DOMXPath($dom);
    $hrefNodes = $xpath->query('//div[@class="filmPoster-1"]/a[contains(@class, "fImg1") and contains(@class, "entityPoster")]/@href');
    
    foreach($hrefNodes as $hrefNode) {
        $links[] = $hrefNode->textContent;
    }
    print_r($links);
    

    正则表达式方式:

    $pattern = <<<'LOD'
    ~
    <div\b
    (?>              # possible content before the class attribute
        [^c>]++      # all that is not a "c" or a ">"
      |              # OR
        \Bc          # a "c" not preceded by a word boundary
      |              # OR
        c(?!lass\b)  # "c" not followed by "lass"
    )++
    class \s*+ = \s*+ ["']?  # the class attribute
    (?-i) filmPoster-1 (?i) (?=["'\s>])
    [^>]*+ > # and of the div tag
    \s*+
    <a\b
    (?>
        [^>h]++
      |
        \Bh
      |
        h(?!ref\b)
    )+
    href \s*+ = \s*+ ["\']?
    \K            # reset all that have been matched before from match result
    [^\s>"\']++
    ~xi
    LOD;
    
    preg_match_all($pattern, $html, $links);
    print_r($links);
    

    【讨论】:

    • 1.显示网站上的所有链接 2. 语法错误,意外的 ']' 但第一种方法对我有帮助,谢谢
    • @Enteee:对不起,我忘记在2中转义单引号。你说你不需要所有的链接,你需要哪些链接?只链接 div 标签内的类 filmPoster?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    • 2013-03-29
    • 1970-01-01
    • 2011-12-31
    • 2011-03-17
    相关资源
    最近更新 更多