2017-03-16 26 views
0

を交換してください:以下のようにすべてのURLを置き換えるために探し私は以下のように私の文字列内のURLを持っているドメイン名の文字列

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

:上記の文字列(URLの+アップ)で

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

が一致するのが一般的です。すべての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 /"もキャッチする必要があります。 –

+0

@DeepanshuGarg:ドメイン名の後に "/ ups /"というURLだけを取得するようにコードを更新しました – 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); 
関連する問題