2017-03-16 60 views
0

我有我的字符串的URL象下面這樣:更換域名字符串

subdomain.domain.com/ups/a/b.gif 
www.domain.com/ups/c/k.gif 
subdomain1.domain.com/ups/l/k.docx 

尋找替代所有網址,如下所示:

anydomain.com/ups/a/b.gif 
anydomain.com/ups/c/k.gif 
anydomain.com/ups/l/k.docx 

在上面的字符串(URL + UPS)是常見的搭配。所有URL都以HTTP或HTTPS啓動。

+1

你看過[parse_url()](http://php.net/manual/en/function.parse-url.php)嗎? –

+0

從標題中刪除標籤名稱 – Shawn

+0

如果有任何答案對您有幫助,您應該加註他們,並將其標記爲已接受最能解答您問題的答案。另請參閱http://stackoverflow.com/help/someone-answers – miken32

回答

0

使用:

$new_string = preg_replace("/(http|https):\/\/(?:.*?)\/ups\//i", "$1://anydomain.com/ups/", $old_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 

輸出將是:

http://anydomain.com/ups/a/b.gif 
https://anydomain.com/ups/c/k.gif 
http://anydomain.com/ups/l/k.docx 
+0

謝謝@Hossam,但它也應該捕獲「/ ups /」。它不應該通過「http://subdomain.domain.com/upss/」工作,而替換 –

+0

@DeepanshuGarg:更新代碼,以便在域名後面僅帶有「/ ups /」的網址 – Hossam

+0

非常感謝你@Hossam。 –

0

你會希望使用正則表達式。

這是怎麼回事正則表達式的解釋:

# /^(http[s]?:\/\/).*?\/(.*)$/ 
# 
#/starting delimiter 
#^match start of string 
# (http[s]?:\/\) match http:// or https:// 
# .*? match all characters until the next matched character 
# \/ match a/slash 
# (.*) match the rest of the string 
# 
# in the replacement 
# 
# $1 = https:// or https:// 
# $2 = path on the url 

$urls = [ 
    'https://subdomain.example.org/ups/a/b.gif', 
    'http://www.example.org/ups/c/k.gif', 
    'https://subdomain1.example.org/ups/l/k.docx' 
]; 

foreach($urls as $key => $url) { 
    $urls[$key] = preg_replace('/^(http[s]?:\/\/).*?\/ups\/(.*)$/', '$1anydomain.com/ups/$2', $url); 
} 

print_r($urls); 

結果

Array 
(
    [0] => https://anydomain.com/ups/a/b.gif 
    [1] => http://anydomain.com/ups/c/k.gif 
    [2] => https://anydomain.com/ups/l/k.docx 
) 
0

正如評論所說,解析URL的方式是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);