Reputation: 2416
I would like to replace the link location (of anchor tag) of a page as follows.
Sample Input:
text text text <a href='http://test1.com/'> click </a> text text
other text <a class='links' href="gallery.html" title='Look at the gallery'> Gallery</a>
more text
Sample Output
text text text <a href='http://example.com/p.php?q=http://test1.com/'> click </a> text text
other text <a class='links' href="http://example.com/p.php?q=gallery.html" title='Look at the gallery'> Gallery</a>
more text
I hope I have make it clear. Anyway I am trying to do it with PHP and reg-ex. Would you please light me up with right.
Thank you Sadi
Upvotes: 1
Views: 1492
Reputation: 21957
Try to use str_replace ();
$string = 'your text';
$newstring = str_replace ('href="', 'href="http://example.com/p.php?q=', $string);
Upvotes: -1
Reputation: 38318
Don't use regular expressions for parsing HTML.
Do use PHP's built-in XML parsing engine. It works quite well on your question (and answers the question to boot):
<?php
libxml_use_internal_errors(true); // ignore malformed HTML
$xml = new DOMDocument();
$xml->loadHTMLFile("http://stackoverflow.com/questions/3099187/replace-links-location-href");
foreach($xml->getElementsByTagName('a') as $link) {
$link->setAttribute('href', "http://www.google.com/?q=" . $link->getAttribute('href'));
}
echo $xml->saveHTML(); // output to browser, save to file, etc.
Upvotes: 9