【问题标题】:How to get links with mp3 as extension如何获取以 mp3 为扩展名的链接
【发布时间】:2013-06-20 21:44:14
【问题描述】:

我有这段代码,它可以从网站中提取所有链接。如何编辑它以使其仅提取以 .mp3 结尾的链接? 以下是以下代码:

preg_match_all("/\<a.+?href=(\"|')(?!javascript:|#)(.+?)(\"|')/i", $html, $matches); 

【问题讨论】:

  • 你试过了吗?
  • 使用 DOM 和以下 xpath://a[ends-with(@href, ".mp3")] - 我想这会容易得多:-)
  • @zerkms XPath, ends-with 听起来比我的回答好得多!之前没有阅读您的评论
  • $xpath = new DOMXPath($doc); $nodes = $xpath-&gt;query('//a[ends-with(@href, ".mp3")]'); -- 将此作为第二个代码添加到您的答案中然后:-)(没有测试,atm 太懒了)
  • @zerkms 做到了。现在是顺时针

标签: php hyperlink extract preg-match-all


【解决方案1】:

更新:

一个不错的解决方案是将DOMXPath 一起使用,正如@zerkms 在cmets 中提到的那样:

$doc = new DOMDocument();
$doc->loadHTML($yourHtml);
$xpath = new DOMXPath($doc); 

// use the XPath function ends-with to select only those links which end with mp3
$links = $xpath->query('//a[ends-with(@href, ".mp3")]/@href');

原答案:

我会为此使用 DOM:

$doc = new DOMDocument();
$doc->loadHTML($yourHtml);

$links = array();
foreach($doc->getElementsByTagName('a') as $elem) {
    if($elem->hasAttribute('href')
    && preg_match('/.*\.mp3$/i', $elem->getAttribute('href')) {
        $links []= $elem->getAttribute('href');
    }
}

var_dump($links);

【讨论】:

    【解决方案2】:

    我更喜欢 XPath,它用于解析 XML/xHTML:

    $DOM = new DOMDocument();
    @$DOM->loadHTML($html); // use the @ to suppress warnings from invalid HTML
    $XPath = new DOMXPath($DOM);
    
    $links = array();
    $link_nodes = $XPath->query('//a[contains(@href, ".mp3")]');
    foreach($link_nodes as $link_node) {
        $source = $link_nodes->getAttribute('href');
        // do some extra work to make sure .mp3 is at the end of the string
    
        $links[] = $source;
    }
    

    如果您使用 XPath 2.0,有一个 ends-with() XPath 函数可以替换 contains()。否则,您可能需要添加额外的条件以确保 .mp3 位于字符串的末尾。不过可能没必要。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-15
      • 1970-01-01
      • 2019-08-18
      • 2014-04-14
      • 1970-01-01
      • 2023-03-05
      • 2019-12-28
      相关资源
      最近更新 更多