替换域名字符串

Dee*_*arg 5 php

我的字符串中有如下 URL:

subdomain.domain.com/ups/a/b.gif
www.domain.com/ups/c/k.gif
subdomain1.domain.com/ups/l/k.docx
Run Code Online (Sandbox Code Playgroud)

希望替换所有 URL,如下所示:

anydomain.com/ups/a/b.gif
anydomain.com/ups/c/k.gif
anydomain.com/ups/l/k.docx
Run Code Online (Sandbox Code Playgroud)

在上面的字符串中(URL + ups)是常见的匹配。所有 URL 都以 HTTP 或 HTTPS 开头。

mik*_*n32 5

正如评论中所建议的,解析 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);
Run Code Online (Sandbox Code Playgroud)


小智 5

也许为时已晚......对于单个字符串:

$components = parse_url( $url);
return str_replace($components['host'], 'anydomain.com', $url);
Run Code Online (Sandbox Code Playgroud)

url 中的协议是必需的。如果 url 是数组 - 在上面循环运行


Hos*_*sam 2

使用:

$new_string = preg_replace("/(http|https):\/\/(?:.*?)\/ups\//i", "$1://anydomain.com/ups/", $old_string);
Run Code Online (Sandbox Code Playgroud)

所以对于输入字符串:

http://subdomain.domain.com/ups/a/b.gif
https://www.domainX.com/ups/c/k.gif
http://subdomain1.domain.com/ups/l/k.docx
Run Code Online (Sandbox Code Playgroud)

输出将是:

http://anydomain.com/ups/a/b.gif
https://anydomain.com/ups/c/k.gif
http://anydomain.com/ups/l/k.docx
Run Code Online (Sandbox Code Playgroud)