如何在PHP中标记html(html作为纯文本)内部获取链接



>我有以下代码

$input = '<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<a class="class1 class2" href="link-to-web1.html">Link</a>
<a class="class1 class2" href="abc/link-to-web1.html">Link</a>
<a class="class1 class2" href="abc/xyz/link-to-web1.html">Link</a>
<a class="another" href="abc/xyz/link.html">Link</a>
</body>
</html>';

使用卷曲后我得到了这个字符串。然后我想获取所有带有类"class1 class2"的标签的所有链接(href 链接),该怎么做?我尝试了一些方法,但它不起作用:(

使用 DOMDocument

$dom = new DOMDocument;
// load your html
$dom->loadHTML($input);
// loop all the anchor tags 
foreach ($dom->getElementsByTagName('a') as $a) {
     // check the calss
     if($a->getattribute('class') == 'class1 class2') {
          // echo href 
          echo $a->getattribute('href')."<br/>";
     }
}

输出:

link-to-web1.html
abc/link-to-web1.html
abc/xyz/link-to-web1.html

最新更新