php获取a链接的href属性的几种方法

时间:2017-10-29
在php中,我们经常要获取一个html文档里面a链接的href属性,这里有几种方法可以实现,本文章向大家介绍php获取a链接的href属性的几种方法,需要的朋友可以参考一下。

php获取a链接的href属性的三种方法。

方法一:正则表达式法

实例代码如下:

$str = '<a title="码农教程" href="http://www.manongjc.com">码农教程</a>';
preg_match('/^<a.*?href=(["\'])(.*?)\1.*$/', $str, $m);
var_dump($m);

运行结果:

array(3) {
  [0]=>
  string(37) "<a title="码农教程" href="http://www.manongjc.com">码农教程</a>"
  [1]=>
  string(1) """
  [2]=>
  string(4) "http://www.manongjc.com"
}

方法二:使用php DOMDocument方法

代码如下:

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

以上代码将输出所有$html变量里面的a标签。

获取a标签文本,可以使用下面代码:

echo $node->nodeValue; 

检查a标签是否存在href属性,可以使用下面代码:

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

使用下面代码获取a标签的href属性值:

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

使用下面代码修改a标签的href属性值:

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

删除a标签的href属性值:

$node->removeAttribute('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
}