抓取A元素的href属性
试图在页面上找到链接。
我的正则表达式是:
/<a\s[^>]*<a href="/tag/href" title="href">href=(\"\'??)([^\"\' >]*?)[^>]*>(.*)<\/a>/但似乎失败了
<a title="this" href="that">what?</a>我该如何更改我的正则表达式以处理未置于a标签首位的href?
回答:
可靠的HTML正则表达式很困难。这是使用DOM的方法:
$dom = new DOMDocument;$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('a') as $node) {
echo $dom->saveHtml($node), PHP_EOL;
}
上面将找到并输出字符串中所有元素的“outerHTML”。A``$html
要 节点的所有文本值,请执行以下操作
echo $node->nodeValue;要 是否href属性存在,你可以做
echo $node->hasAttribute( 'href' );为了 该href你做的属性
echo $node->getAttribute( 'href' );要 的href属性,你会怎么做
$node->setAttribute('href', 'something else');要 的href,你会怎么做属性
$node->removeAttribute('href');您也可以href直接使用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
}
以上是 抓取A元素的href属性 的全部内容, 来源链接: utcz.com/qa/425329.html

