V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
SkyRing
V2EX  ›  PHP

怎么把原来的 url 得到的某个地址,替换其中的域名呢?

  •  
  •   SkyRing · 2022-12-10 11:33:52 +08:00 · 2266 次点击
    这是一个创建于 474 天前的主题,其中的信息可能已经有所发展或是发生改变。

    比如原来$url 得到 xxx.com/sadasd.jpg ,想要变成 aaa.com/sadasd.jpg ,这样子,怎么弄呢?

    9 条回复    2022-12-12 09:07:19 +08:00
    GreatAuk
        1
    GreatAuk  
       2022-12-10 11:54:47 +08:00
    const url = new URL('https://www.v2ex.com/t/901497#reply0')
    url.host = 'www.baidu.com'
    console.log(url.href)
    muzihuaner
        2
    muzihuaner  
       2022-12-10 11:57:10 +08:00 via Android
    可以问一下 chatgpt😂
    dongisking
        3
    dongisking  
       2022-12-10 12:03:30 +08:00
    ```
    $str = 'xxx.com/sadasd.jpg';
    $replace = 'aa.com';
    $search = 'xxx.com';
    echo str_ireplace($search, $replace, $str);
    ```
    Thecosy
        4
    Thecosy  
       2022-12-10 12:28:25 +08:00
    @muzihuaner 如果你想替换 URL 中的域名,你可以使用字符串操作来构造新的 URL 。下面是一个示例:

    Copy code
    // Define the old and new domain names
    const oldDomain = "old-domain.com";
    const newDomain = "new-domain.com";

    // Define the URL
    const url = "http://old-domain.com/path/to/page.html";

    // Replace the domain name in the URL
    const newUrl = url.replace(oldDomain, newDomain);

    // Print the new URL
    console.log(newUrl); // "http://new-domain.com/path/to/page.html"
    在这个例子中,我们定义了原来的域名和新的域名,然后使用 String.replace() 方法来替换 URL 中的域名。

    希望这对你有帮助!
    来自 chatgpt
    neotheone2333
        5
    neotheone2333  
       2022-12-10 12:36:37 +08:00
    可以多问一句:我想要一个更通用的方法

    如果你想要一个更通用的方法来替换 URL 中的域名,那么你可以使用一个函数来实现。例如,下面是一个简单的函数,它可以接收一个 URL 和一个新的域名,然后返回替换后的 URL 。

    Copy code
    function replaceDomain(url, newDomain) {
    let oldDomain = /[^/]*?(?=\/)/;
    return url.replace(oldDomain, newDomain);
    }
    在这个函数中,我们首先使用正则表达式 /[^/]*?(?=\/)/ 来匹配 URL 中的域名。这个正则表达式的工作原理是,先匹配所有不含斜杠的字符,然后在后面加上一个非贪婪的匹配,用来匹配第一个出现的斜杠。

    然后,我们使用 replace 方法来替换原来的域名。最后,我们返回替换后的 URL 。

    下面是一个使用这个函数的例子:

    Copy code
    let oldUrl = 'xxx.com/sadasd.jpg';
    let newUrl = replaceDomain(oldUrl, 'aaa.com');
    console.log(newUrl); // 输出 aaa.com/sadasd.jpg
    希望这些信息能够帮助你。如果你还有其他问题,请继续提问。
    hqt1021
        6
    hqt1021  
       2022-12-10 12:41:09 +08:00   ❤️ 1
    @Thecosy 卧槽?真 tm 来 ChatGPT
    ChoateYao
        7
    ChoateYao  
       2022-12-10 14:07:34 +08:00
    用 parse_url 想想怎么替换就怎么替换。
    SkyRing
        8
    SkyRing  
    OP
       2022-12-10 14:47:58 +08:00
    有点看不懂,我还是抽空在补习一下好了。不过解决了,虽然是 js 随便糊了一下。先用着好了。
    jifengg
        9
    jifengg  
       2022-12-12 09:07:19 +08:00
    一楼已经给了 js 的标准答案
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5483 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 08:20 · PVG 16:20 · LAX 01:20 · JFK 04:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.