【问题标题】:Parse All Links That Contain A Specific Word In "href" Tag [duplicate]解析“href”标签中包含特定单词的所有链接[重复]
【发布时间】:2012-01-02 17:47:12
【问题描述】:

可能重复:
Grabbing the href attribute of an A element

我需要解析包含某个单词的 HTML 文档的所有链接(总是不同的)。

例子:

<a href="/bla:bla">BLA</a>
<a href="/link:link">BLA</a>
<a href="/link:bla">BLA</a>

我只需要带有“href=/link: ....”的链接,最好的方法是什么?

$html = "SOME HTLM ";
$dom = new DomDocument();
@$dom->loadHTML($html);
$urls = $dom->getElementsByTagName('a');
foreach ($urls as $url)
{
    echo "<br> {$url->getAttribute('href')} , {$url->getAttribute('title')}";
    echo "<hr><br>";
}

在这个例子中显示了所有链接,我需要特定的链接。

【问题讨论】:

    标签: php parsing


    【解决方案1】:

    使用正则表达式。

    foreach ($urls as $url)
    {
        $href = $url->getAttribute('href');
        if (preg_match("/^\/link:/",$href){
            $links[$url->getAttribute('title')] = $href;
        }
    }
    

    $links 数组包含所有匹配的标题和 href。

    【讨论】:

    • 正则表达式是相对昂贵的操作,应尽可能避免在循环中使用它们。 substr() 在这种情况下很好。
    • 没错,但从他的设置来看,我有一种奇怪的感觉,以后会变得更复杂。
    • 在真正需要之前无需增加复杂性 :)
    【解决方案2】:

    通过使用条件。

    <?php 
    $lookfor='/link:';
    
    foreach ($urls as $url){
        if(substr($url->getAttribute('href'),0,strlen($lookfor))==$lookfor){
            echo "<br> ".$url->getAttribute('href')." , ".$url->getAttribute('title');
            echo "<hr><br>";
        }
    }
    ?>
    

    【讨论】:

      【解决方案3】:

      由于 getAttribute 只返回一个字符串,因此您只需使用 strpos() 检查它以什么开头。

      $href = $url -> getAttrubute ('href');
      if (strpos ($href, '/link:') === 0)
      {
          // Do your processing here
      }
      

      【讨论】:

        【解决方案4】:

        您可以使用XPath 直接在文档中查询这些节点,而不是先获取所有 a 元素然后过滤掉您需要的元素:

        //a[contains(@href, "link:")]
        

        此查询将在 包含 href 属性 字符串 link: 的文档中找到 所有 a 元素 >。

        检查href属性是否开头的链接:可以这样做

        //a[starts-with(@href, "link:")]
        

        完整示例 (demo):

        $dom = new DomDocument();
        $dom->loadHTML($html);
        $xpath = new DOMXPath($dom);
        foreach ($xpath->query('//a[contains(@href, "link:")]') as $a) {
            echo $a->getAttribute('href'), PHP_EOL;
        }
        

        另请参阅

        相关问题。

        注意:标记此 CW 是因为有许多相关问题

        【讨论】:

        • 谢谢。你能解释一下“CW”是什么吗?
        • @Ron CW = 社区维基。我没有从中获得声誉。
        猜你喜欢
        • 2021-03-11
        • 1970-01-01
        • 1970-01-01
        • 2014-09-23
        • 1970-01-01
        • 1970-01-01
        • 2016-03-09
        • 1970-01-01
        相关资源
        最近更新 更多