【问题标题】:Extract the href from a url with a class using PHP?使用PHP从带有类的url中提取href?
【发布时间】:2011-05-25 15:27:59
【问题描述】:

这有可能吗……

假设我有一些带有“点击”类链接的文本:

<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,获取类名的链接,'点击',然后获取href值?

【问题讨论】:

标签: php hyperlink extract href


【解决方案1】:

有几种方法可以做到这一点,最快的是使用 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;
}

【讨论】:

    【解决方案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];
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-18
    • 2017-04-01
    • 2013-10-28
    • 2012-08-02
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多