]*?)[^>]*>(.*)/ 但似乎失败了 what? 我将如何更改我的正则表达式以处理未放在 a 标签-6ren">
gpt4 book ai didi

php - 获取 A 元素的 href 属性

转载 作者:行者123 更新时间:2023-11-28 03:42:29 24 4
gpt4 key购买 nike

试图找到页面上的链接。

我的正则表达式是:

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

但似乎失败了

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

我将如何更改我的正则表达式以处理未放在 a 标签中第一位的 href?

最佳答案

Reliable Regex for HTML are difficult .这是使用 DOM 的方法:

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

上面会找到并输出 "outerHTML" $html 字符串中的所有 A 元素。

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

echo $node->nodeValue; 

检查 href 属性是否存在,您可以这样做

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

获取 href 属性

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

更改 href 属性你会做

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

删除 href 属性,您需要这样做

$node->removeAttribute('href'); 

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

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

另见:

旁注:我确定这是重复的,您可以 find the answer somewhere in here

关于php - 获取 A 元素的 href 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9507905/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com