hsatterwhite
hsatterwhite

Reputation: 7355

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

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

Upvotes: 2

Views: 495

Answers (1)

VolkerK
VolkerK

Reputation: 96199

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>

Upvotes: 5

Related Questions