user2307392
user2307392

Reputation: 57

How to replace a href links in php

I need to replace all <a> hrefs with some text in a php file. I have used

preg_replace('#\s?<a.*/a>#', 'text', $string);

But this replaces all links with the same text. I need different texts for each links. How to achieve this. Also is it possible to get the href link fully, means if i have a file containing the link <a href="www.google.com">Google</a>, how can i extract the string '<a href="www.google.com">Google</a>'.

Please help me.

Upvotes: 0

Views: 1625

Answers (2)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76395

OK, since there's no clear answer on how to manipulate the DOM in the way, I think, you want to manipulate it:

$foo = '<body><p> Some BS and <a href="https://www.google.com"> Link!</a></p></body>';
$dom = new DOMDocument;
$dom->loadHTML($foo);//parse the DOM here
$links = $dom->getElementsByTagName('a');//get all links
foreach($links as $link)
{//$links is DOMNodeList instance, $link is DOMNode instance
    $replaceText = $link->nodeValue.': '.$link->getAttribute('href');//inner text: href attribute
    $replaceNode = $dom->createTextNode($replaceText);//create a DOMText instance
    $link->parentNode->replaceChild($replaceNode, $link);//replace the link with the DOMText instance
}
echo $dom->saveHTML();//echo the HTML after edits...

This puts out:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><p> Some BS and  Link!: https://www.google.com</p></body></html>

Just Start by reading the DOMDocument manual, and click through to all methods (and related classes) that I'm using here. The DOMDocument API, like the DOM API in client-side JS, is bulky and not really that intuitive, but that's just how it is...
Echoing the actual html,without the doctype can be done using the saveXML method, and/or some string operations... all in all, it shouldn't be too difficult to get to where you want, using this code as a basis, and the links provided.

Upvotes: 1

metalfight - user868766
metalfight - user868766

Reputation: 2750

Use DOMDocument.

$dom = new DOMDocument;
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('a') as $node) {
    //Do your processing here
}

Upvotes: 1

Related Questions