Php 解析“中包含特定单词的所有链接”;href";标签

Php 解析“中包含特定单词的所有链接”;href";标签,php,parsing,Php,Parsing,可能重复: 我需要解析包含某个单词的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(); @$d

可能重复:

我需要解析包含某个单词的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>";
}
$html=“SOME HTLM”;
$dom=新的DomDocument();
@$dom->loadHTML($html);
$URL=$dom->getElementsByTagName('a');
foreach($url作为$url)
{
echo“
{$url->getAttribute('href')},{$url->getAttribute('title')}”; 回声“

”; }

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

使用正则表达式

foreach ($urls as $url)
{
    $href = $url->getAttribute('href');
    if (preg_match("/^\/link:/",$href){
        $links[$url->getAttribute('title')] = $href;
    }
}
$links数组包含所有匹配的标题和href。

使用条件

<?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>";
    }
}
?>

因为getAttribute只返回一个字符串,您只需检查它以strpos()开头的内容即可


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

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

要检查href属性是否以link开头,请执行以下操作

//a[starts-with(@href, "link:")]
完整示例(): 另请参阅

有关问题


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

正则表达式是相对昂贵的操作,如果可能,应避免在循环中使用它们。substr()在这种情况下很好。没错,但从他的设置来看,我有一种奇怪的感觉,以后它会变得更复杂。在真正需要之前,不需要增加复杂性:)谢谢。你能解释一下“CW”是什么吗?@Ron CW=社区Wiki。我从中得不到名声。
//a[contains(@href, "link:")]
//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;
}