小编典典

抓取A元素的href属性

html

试图在页面上找到链接。

我的正则表达式是:

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

但似乎失败了

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

我该如何更改我的正则表达式以处理未置于a标签首位的href?


阅读 800

收藏
2020-05-10

共1个答案

小编典典

可靠的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
}
2020-05-10