开发者

How can you find all HTML hyper link tags in a string and replace them with their href value?

开发者 https://www.devze.com 2022-12-27 13:24 出处:网络
I\'d like to take a string of text and find all of 开发者_Go百科the hyper link tags, grab their href value, and replace the entire hyper link tag with the value of the href attribute.Many possibilitie

I'd like to take a string of text and find all of 开发者_Go百科the hyper link tags, grab their href value, and replace the entire hyper link tag with the value of the href attribute.


Many possibilities. E.g. by using the DOM extension, DOMDocument::loadhtml() and XPath (though getElementsbyTagName() would suffice in this case).

<?php
$string = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"><html><head><title>...</title></head><body>
  <p>
    mary had a <a href="little">greedy</a> lamb
    whose fleece was <a href="white">cold</a> as snow
  </p>
</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();

prints

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head><title>...</title></head>
<body><p>
    mary had a little lamb
    whose fleece was white as snow
  </p></body>
</html>
0

精彩评论

暂无评论...
验证码 换一张
取 消