作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
]*?)[^>]*>(.*)/ 但似乎失败了 what? 我将如何更改我的正则表达式以处理未放在 a 标签-6ren">
试图找到页面上的链接。
我的正则表达式是:
/<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/
我是一名优秀的程序员,十分优秀!