获取A元素的href属性 [英] Grabbing the href attribute of an A element

查看:352
本文介绍了获取A元素的href属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图在页面上查找链接。

Trying to find the links on a page.

我的正则表达式是:

/<a\s[^>]*href=(\"\'??)([^\"\' >]*?)[^>]*>(.*)<\/a>/

但似乎在

<a title="this" href="that">what?</a>

如何更改我的正则表达式来处理首先放在标签中的href?

How would I change my regex to deal with href not placed first in the a tag?

推荐答案

HTML的可靠正则表达式是困难的。以下是 DOM 的使用方法:

Reliable Regex for HTML are difficult. Here is how to do it with DOM:

$dom = new DOMDocument;
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('a') as $node) {
    echo $dom->saveHtml($node), PHP_EOL;
}

以上将找到并输出 A 中的元素的stackoverflow.com/questions/5404941/php-domdocument-outerhtml-for-element/5404962#5404962\">\"outerHTML, code> $ html string。

The above would find and output the "outerHTML" of all A elements in the $html string.

获取节点的所有文本值,您可以执行

To get all the text values of the node, you do

echo $node->nodeValue; 

如果 href 属性存在你可以做

To check if the href attribute exists you can do

echo $node->hasAttribute( 'href' );

获取 href 属性你可以做

echo $node->getAttribute( 'href' );

更改 href 属性你会做

$node->setAttribute('href', 'something else');

删除 href 属性你可以做

$node->removeAttribute('href'); 

您还可以查询 href 属性直接使用 XPath

You can also query for the href attribute directly with XPath

$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//a/@href');
foreach($nodes as $href) {
    echo $href->nodeValue;                       // echo current attribute value
    $href->nodeValue = 'new value';              // set new attribute value
    $href->parentNode->removeAttribute('href');  // remove attribute
}

另见:

  • Best methods to parse HTML
  • DOMDocument in php

在sidenote:我相信这是重复的,你可以在这里找到答案

这篇关于获取A元素的href属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆