
獲取 A 元素的 href 屬性
為了在頁面上查找鏈接,常見的方法是使用正則表達式。然而,在這樣的情況下:
1 | <a title= "this" href= "that" >what?</a>
|
登入後複製
href 屬性沒有放在a 標籤的最前面,以下正規表示式可能會失敗:
1 | /<a\s[^>]*href=(\"\'??)([^\"\' >]*?)[^>]*>(.*)<\/a>/
|
登入後複製
為處理HTML 可能具有挑戰性。作為替代方案,請考慮使用 DOM(文件物件模型)來實現此目的。
使用 DOM 處理 HTML
以下是如何使用 DOM 從 A 檢索 href屬性與其他資訊elements:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | $dom = new DOMDocument;
$dom ->loadHTML( $html );
foreach ( $dom ->getElementsByTagName( 'a' ) as $node ) {
echo $dom ->saveHtml( $node ), PHP_EOL;
echo $node ->nodeValue;
echo $node ->hasAttribute( 'href' );
echo $node ->getAttribute( 'href' );
$node ->setAttribute( 'href' , 'something else' );
$node ->removeAttribute( 'href' );
}
|
登入後複製
使用XPath查詢href屬性
XPath也可以用來查詢特定的屬性,例如href屬性:
1 2 3 4 5 6 7 8 9 10 11 | $dom = new DOMDocument;
$dom ->loadHTML( $html );
$xpath = new DOMXPath( $dom );
$nodes = $xpath ->query( '//a/@href' );
foreach ( $nodes as $href ) {
echo $href ->nodeValue;
$href ->nodeValue = 'new value' ;
$href ->parentNode->removeAttribute( 'href' );
}
|
登入後複製
結論
使用DOM,可以輕鬆檢索和操作諸如來自A 元素的href 之類的屬性。這種方法提供了比正規表示式更可靠、更靈活的 HTML 處理方式。
以上是如何從 HTML 中的 `` 元素可靠地檢索 `href` 屬性?的詳細內容。更多資訊請關注PHP中文網其他相關文章!