一千萬個為什麽

搜索

如何在字符串中找到所有HTML超鏈接標記並用它們的href值替換它們?

我想獲取一串文本並查找所有超鏈接標記,獲取其href值,並使用href屬性的值替換整個超鏈接標記。

最佳答案

很多可能性。例如。使用 DOM擴展DOMDocument :: loadhtml()XPath (雖然getElementsbyTagName()在這種情況下就足夠了)。

<?php
$string = '<html><head><title>...</title></head><body>
  
mary had a greedy lamb whose fleece was cold as snow

</body></html>'; $doc = new DOMDocument; $doc->loadhtml($string); $xpath = new DOMXPath($doc); foreach( $xpath->query('//a') as $a ) { $tn = $doc->createTextNode($a->getAttribute('href')); $a->parentNode->replaceChild($tn, $a); } echo $doc->savehtml();

版畫


<html>
<head><title>...</title></head>
<body>
mary had a little lamb whose fleece was white as snow

</body> </html>

轉載註明原文: 如何在字符串中找到所有HTML超鏈接標記並用它們的href值替換它們?