可能重复:
获取A元素的href属性
我需要解析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
$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>";
}
}
?>
您可以使用XPath:直接在文档中查询这些节点,而不是先获取所有的a元素,然后过滤掉所需的元素
//a[contains(@href, "link:")]
此查询将在文档中查找所有元素,包含href属性中的字符串链接。
要检查href属性是否以链接开头:您可以执行
//a[starts-with(@href, "link:")]
完整示例(演示(:
$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;
}
另请参阅
- XPath中的实现条件
- 从路径链接中排除URL
- PHP/XXPath:查找文本节点;以";一个特定的字符串
- PHP Xpath:获取所有包含针的href值
相关问题。
注意:标记此CW是因为有许多相关问题
使用正则表达式。
foreach ($urls as $url)
{
$href = $url->getAttribute('href');
if (preg_match("/^'/link:/",$href){
$links[$url->getAttribute('title')] = $href;
}
}
$links数组包含所有匹配的标题和href。
由于getAttribute只返回一个字符串,您只需要检查它以strpos((开头的内容。
$href = $url -> getAttrubute ('href');
if (strpos ($href, '/link:') === 0)
{
// Do your processing here
}