I have URLs in my string like below:
subdomain.domain.com/ups/a/b.gif
www.domain.com/ups/c/k.gif
subdomain1.domain.com/ups/l/k.docx
Looking to replace all URL like below:
anydomain.com/ups/a/b.gif
anydomain.com/ups/c/k.gif
anydomain.com/ups/l/k.docx
In above string (URL + ups) is common to match. All URLs are started with either HTTP or HTTPS.
As suggested in comments, the way to parse URLs is with parse_url()
.
<?php
$urls = [
"http://subdomain.domain.com/ups/a/b.gif",
"https://www.example.com/ups/c/k.gif",
"https://subdomain1.domain.com/ups/l/k.docx",
];
$domain = "anydomain.com";
foreach ($urls as &$url) {
$u = parse_url($url);
$url = "$u[scheme]://$domain$u[path]" . (isset($u["query"]) ? "?$u[query]" : "");
}
print_r($urls);
Maybe it's too late... For a single string:
$components = parse_url( $url);
return str_replace($components['host'], 'anydomain.com', $url);
Protocol in url required. If urls are array - run above in a loop
use:
$new_string = preg_replace("/(http|https):\/\/(?:.*?)\/ups\//i", "$1://anydomain.com/ups/", $old_string);
so for input string:
http://subdomain.domain.com/ups/a/b.gif
https://www.domainX.com/ups/c/k.gif
http://subdomain1.domain.com/ups/l/k.docx
the output will be:
http://anydomain.com/ups/a/b.gif
https://anydomain.com/ups/c/k.gif
http://anydomain.com/ups/l/k.docx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With