i am trying to replace all the URL in webpage using PHP.
Let say the website content several different links some with https, some with http, some with www or non-www or different domain or sub domain. and i want to replace all of the website link to my custom link.
Code :
$homepage = file_get_contents("https://www.example.com");
$homepage = str_replace('#href="(.*)"#', 'href="https://example.net"', $homepage);
echo $homepage;
I have also tried preg_replace instead of str_replace like this
$homepage = preg_replace('#href="(.*)"#', 'href="https://example.net"', $homepage);
Edited :
I want to change URL of image and text. Not CSS, JS file or Link tag.
Is it possible, so it only change the link instead
<body> </body>and do not touch anything inside<head> </head>
CodePudding user response:
I would just use a <a href="<?php echo $homepage;?>">Text </a> and and get as change Text to the name you wanna display and for Text you can use
$url = 'http://en.example.com';
$parsedUrl = parse_url($url);
$host = explode('.', $parsedUrl['host']);
$hosts=count($host)-2;
$lastdomain = $host[$hosts];
echo $lastdomain;
CodePudding user response:
Try like this regex below.
$replacer = 'href="https://example.net"';
$homepage = preg_replace_callback('/<body.*?>(.*)<\/body>/', function($matches) use($replacer) {
return preg_replace("/(?<=href=(\"|'))[^\"'] (?=(\"|'))/",$replacer,$matches[0]);
},$homepage);
echo $homepage;
you can view the fiddle here
