使用 PHP 从类中提取 href?

发布于 2024-10-08 00:12:09 字数 334 浏览 0 评论 0原文

这是否可能...

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

<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,获取类名“click”的链接,然后获取 href 值?

Is this even possible...

Say I have some text with a link with a class of 'click':

<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>

Using PHP, get the link with class name, 'click', then get the href value?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

山色无中 2024-10-15 00:12:10

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

There are a few ways to do this, the quickest is to use 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;
}
青巷忧颜 2024-10-15 00:12:10

实际上你根本不需要让你的生活变得复杂:

$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];
}

You actually don't need to complicate your life at all:

$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];
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文