我的字符串中包含以下网址:
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启动。
答案 0 :(得分:1)
正如评论中所建议的,解析网址的方式是使用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);
答案 1 :(得分: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
答案 2 :(得分: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
)
答案 3 :(得分:0)
也许为时已晚... 对于单个字符串:
$components = parse_url( $url);
return str_replace($components['host'], 'anydomain.com', $url);
必须输入网址中的协议。 如果网址是数组-循环运行以上