簡體   English   中英

抓取A元素的href屬性

[英]Grabbing the href attribute of an A element

試圖在頁面上找到鏈接。

我的正則表達式是:

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

但似乎失敗了

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

我該如何更改我的正則表達式以處理未置於a標簽首位的href?

可靠的HTML正則表達式很難 這是使用DOM的方法

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

上面的代碼將找到並輸出$html字符串中所有A元素的“ outerHTML”

獲取節點的所有文本值,請執行以下操作

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
}

另請參閱:

在旁注:我確定這是重復的,您可以在這里的某個地方找到答案

我同意戈登的觀點,您必須使用HTML解析器來解析HTML。 但是,如果您真的想要正則表達式,可以嘗試以下方法:

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

這在字符串的開頭匹配<a ,后跟任意數量的任何字符(非貪婪) .*? 然后href=后跟用"'包圍的鏈接

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

輸出:

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

您要查找的模式將是鏈接錨模式,例如(某物):

$regex_pattern = "/<a href=\"(.*)\">(.*)<\/a>/";

你為什么不匹配

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

<?php

$str = '<a title="this" href="that">what?</a>';

$res = array();

preg_match_all("/<a.*?href\s*=\s*['\"](.*?)['\"]/", $str, $res);

var_dump($res);

?>

然后

$ php test.php
array(2) {
  [0]=>
  array(1) {
    [0]=>
    string(27) "<a title="this" href="that""
  }
  [1]=>
  array(1) {
    [0]=>
    string(4) "that"
  }
}

哪個有效。 我剛剛刪除了第一個捕獲括號。

對於仍然無法使用SimpleXML輕松獲得解決方案的人

$a = new SimpleXMLElement('<a href="www.something.com">Click here</a>');
echo $a['href']; // will echo www.something.com

它為我工作

我不確定您要在這里做什么,但是如果您要驗證鏈接,請查看PHP的filter_var()

如果您確實需要使用正則表達式,請查看此工具,它可能會有所幫助: http : //regex.larsolavtorvik.com/

使用您的正則表達式,我對其做了一些修改以滿足您的需要。

<a.*?href=("|')(.*?)("|').*?>(.*)<\\/a>

我個人建議您使用HTML解析器

編輯:經過測試

快速測試: <a\\s+[^>]*href=(\\"\\'??)([^\\1]+)(?:\\1)>(.*)<\\/a>似乎可以技巧,第一個匹配為“或”,第二個為“ href”值“ that”,第三個為“ what?”。

我之所以將第一個匹配項“ /”留在其中是因為以后可以使用它反向引用以結束“ /”,因此它是相同的。

參見以下示例: http : //www.rubular.com/r/jsKyK2b6do

preg_match_all( “/(]>)()(</ A)/?”,$內容,$ impmatches,PREG_SET_ORDER);

經過測試,它可以從任何html代碼中提取所有標簽。

以下內容對我href並且同時返回href標簽和href value

preg_match_all("'\<a.*?href=\"(.*?)\".*?\>(.*?)\<\/a\>'si", $html, $match);
if($match) {
    foreach($match[0] as $k => $e) {
        $urls[] = array(
            'anchor'    =>  $e,
            'href'      =>  $match[1][$k],
            'value'     =>  $match[2][$k]
        );
    }
}

名為$urls的多維數組現在包含易於使用的關聯子數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM