使用PHP从类中提取href?

时间:2010-12-15 00:28:45

标签: php hyperlink extract href

这甚至可能......

说我有一些文字,其中包含一个'点击':

类的链接
<p>I am some text, i am some text, i am some text, i am some text
<a class="click" href="http://www.google.com">I am a link</a>
i am some text, i am some text, i am some text, i am some text</p>

使用PHP,获取带有班级名称的链接,然后点击&#39;,然后获取href值?

2 个答案:

答案 0 :(得分:6)

有几种方法可以做到这一点,最快的方法是使用XPath:

$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);

$nodeList = $xpath->query('//a[@class="click"]');
foreach ($nodeList as $node) {
    $href = $node->getAttribute('href');
    $text = $node->textContent;
}

答案 1 :(得分:2)

你根本不需要让生活复杂化:

$string='that html code with links';
// while matches found
while(preg_match('/<a class="click" href="([^"]*)">/', $string, $matches)){
    // print captured group that's actually the url your searching for
    echo $matches[1];
}