Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace domain name string

Tags:

php

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.

like image 373
Deepanshu Garg Avatar asked Mar 16 '17 17:03

Deepanshu Garg


3 Answers

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);
like image 100
miken32 Avatar answered Nov 02 '22 13:11

miken32


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

like image 40
David Evdoschenko Avatar answered Nov 02 '22 14:11

David Evdoschenko


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
like image 2
Hossam Avatar answered Nov 02 '22 13:11

Hossam