繁体   English   中英

从匹配的锚文本中获取href值

[英]Get href value from matching anchor text

我是DOMDocument类的新手,似乎找不到我要做什么的答案。

我有一个很大的html文件,我想从基于锚文本的元素中获取链接。

例如

$html = <<<HTML
<div class="main">
    <a href="http://link.com" target="blank" ><span><font style="color: #e7552c;"><img src="http://images.com/spacer.gif"/>Keyword</font></span></a>
    other text
</div>
HTML;

// domdocument
$doc = new DOMDocument();
$doc->loadHTML($html);

我想获取具有text 关键字的任何元素的href属性的值。 希望很清楚

$html = <<<HTML
<div class="main">
    <a href="http://link.com" target="blank" ><span><font style="color: #e7552c;"><img src="http://images.com/spacer.gif"/>Keyword</font></span></a>
    other text
</div>
HTML;

$keyword = "Keyword";

// domdocument
$doc = new DOMDocument();
$doc->loadHTML($html);
$as = $doc->getElementsByTagName('a');
foreach ($as as $a) {
    if ($a->nodeValue === $keyword) {
        echo $a->getAttribute('href'); // prints "http://link.com"
        break;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM