【问题标题】:PHP: DOM get url and anchors (but not IMG)PHP:DOM 获取 url 和锚点(但不是 IMG)
【发布时间】:2013-07-13 00:30:50
【问题描述】:

我想将 HTML 页面中的所有 URL 选择到一个数组中,例如:

This is a webpage <a href="http://somesite.com/link1.php">with</a> 
different kinds of <a href="http://somesite.com/link1.php"><img src="someimg.png"></a>

我想要的输出是:

with => http://somesite.se/link1.php

现在我明白了:

<img src="someimg.png"> => http://somesite.com/link1.php
with => http://somesite.com/link1.php

我不希望在 start 和 end 之间包含图像的 url/链接。只有那些有文字的。

我当前的代码是:

<?php

function innerHTML($node) {
    $ret = '';

    foreach ($node->childNodes as $node) {
        $ret .= $node->ownerDocument->saveHTML($node);
    }

    return $ret;
}

$html = file_get_contents('http://somesite.com/'.$_GET['apt']);

$dom = new DOMDocument;
@$dom->loadHTML($html); // @ = Removes errors from the HTML...
$links = $dom->getElementsByTagName('a');
$result = array();

foreach ($links as $link) {
    //$node = $link->nodeValue;
    $node = innerHTML($link);
    $href = $link->getAttribute('href');

    if (preg_match('/\.pdf$/i', $href))
            $result[$node] = $href;
}

print_r($result);

?>

【问题讨论】:

    标签: php url dom hyperlink


    【解决方案1】:

    在条件中添加第二个preg_match

    if(preg_match('/\.pdf$/i',$href) && !preg_match('/<img .*>/i',$node)) $result[$node] = $href;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-01
      • 1970-01-01
      • 2011-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多