I am trying to replace the urls of a web page. I am using DOM to get all the links in the page, loop through the links and find and replace one by one using str_ireplace. The str_ireplace replaces only the last link. When I count, it gives proper count of the number of links to be replaced, but does not replace the links.
$contents=file_get_contents($_GET['page']);
$dom = new DOMDocument;
@$dom->loadHTML($contents);
$links = $dom->getElementsByTagName('a');
$c=0;
//Iterate over the extracted links and display their URLs
foreach ($links as $link){
//echo $link->nodeValue;
$arr['retUrl']=$link->getAttribute('href');
$xyz=json_encode($arr);
$rurl=$base_url.'?ret_url='.urlencode($xyz);
echo $arr['retUrl'].'<br>'.$rurl.'<br><br><br>';
$x=str_ireplace($link->getAttribute('href'),$rurl,$contents,$count);
$c=$c+$count;
echo '--'.$count.'--';
}
echo $x;