抓取A元素的href属性

ber*_*gin 113 html php dom

试图在页面上找到链接.

我的正则表达式是:

/<a\s[^>]*href=(\"\'??)([^\"\' >]*?)[^>]*>(.*)<\/a>/
Run Code Online (Sandbox Code Playgroud)

但似乎失败了

<a title="this" href="that">what?</a>
Run Code Online (Sandbox Code Playgroud)

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

Gor*_*don 207

HTML的可靠正则表达式很难.以下是如何使用DOM:

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

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

获取节点的所有文本值,请执行此操作

echo $node->nodeValue; 
Run Code Online (Sandbox Code Playgroud)

检查是否href属性存在,你可以做

echo $node->hasAttribute( 'href' );
Run Code Online (Sandbox Code Playgroud)

为了获得href你做的属性

echo $node->getAttribute( 'href' );
Run Code Online (Sandbox Code Playgroud)

更改href您要执行的属性

$node->setAttribute('href', 'something else');
Run Code Online (Sandbox Code Playgroud)

删除href您要执行的属性

$node->removeAttribute('href'); 
Run Code Online (Sandbox Code Playgroud)

您还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
}
Run Code Online (Sandbox Code Playgroud)

另见:

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


Tot*_*oto 19

我同意Gordon,你必须使用HTML解析器来解析HTML.但如果你真的想要一个正则表达式,你可以尝试这个:

/^<a.*?href=(["\'])(.*?)\1.*$/
Run Code Online (Sandbox Code Playgroud)

这匹配<a在字符串的开头,后跟任意数量的任何字符(非贪婪),.*?然后href=是由任意一个"或包围的链接'

$str = '<a title="this" href="that">what?</a>';
preg_match('/^<a.*?href=(["\'])(.*?)\1.*$/', $str, $m);
var_dump($m);
Run Code Online (Sandbox Code Playgroud)

输出:

array(3) {
  [0]=>
  string(37) "<a title="this" href="that">what?</a>"
  [1]=>
  string(1) """
  [2]=>
  string(4) "that"
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*tau 5

您要查找的模式将是链接锚点模式,如(某些):

$regex_pattern = "/<a href=\"(.*)\">(.*)<\/a>/";
Run Code Online (Sandbox Code Playgroud)