【问题标题】:How can I change the scheme of a URL with preg_match? [duplicate]如何使用 preg_match 更改 URL 的方案? [复制]
【发布时间】:2013-02-05 11:13:04
【问题描述】:

可能重复:
How to add http:// if it’s not exists in the URL?

假设我想匹配一个可能包含 http://https:// 或两者都没有的 URL。当我替换它时,如果有https://,我希望它在前面,但如果它是http://,或者什么都没有,我希望在开头有http://

我不知道如何使用 preg_match 表达式来解决这个问题,或者对于非 PHP 倾向,一个搜索和替换 PHP 函数。

【问题讨论】:

标签: php regex


【解决方案1】:

您可以使用preg_replace_callback,并编写一个函数来执行此操作。

【讨论】:

    【解决方案2】:

    如果你想要一个正则表达式解决方案,这样的事情应该可以工作。

    preg_replace('|^(?:http(s)?://)?(.+)$|', 'http\\1://\\2', $url);

    虽然我可能会使用 parse_url 并将其重新组合在一起。

    【讨论】:

    • 我的问题在于没有任何 http:// 或 https:// 的 URL,例如 www.stackoveflow.com
    • 你试过了吗? echo preg_replace('|^(?:http(s)?://)?(.+)$|', 'http\\1://\\2', 'www.stackoverflow.com');
    猜你喜欢
    • 2012-07-06
    • 1970-01-01
    • 2010-11-25
    • 1970-01-01
    • 2016-02-05
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    相关资源
    最近更新 更多