How can you find all the HTML hyperlink links in a string and replace them with your href value?

I would like to take a line of text and find all the hyperlink tags, grab their href value, and replace the entire hyperlink tag with the href attribute value.

+2


a source to share


1 answer


A lot of possibilities. For instance. using the DOM extension , DOMDocument :: loadhtml () and XPath (although getElementsbyTagName () will 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>

      

+5


a source







All Articles