如果它们没有退出,请将https:// protocol和www子域添加到输入url?

时间:2015-11-10 13:12:37

标签: php regex

我有一个接受网址输入的表单。 无论输入的格式是什么,我都希望使用以下格式的URL。

  

https://www.example.com

因此,如果有人输入以下链接,我想将它们转换为格式

  

example.com

     

http://example.com

     

https://example.com

     

http://www.example.com

如果他们以正确的格式输入,则无需更改网址。

以下是我尝试但未能成功的事。

//append https:// and www to URL if not present
    if (!preg_match("~^(?:f|ht)tps?://~i", $url0) OR strpos($url0, "www") == false) {
        if ((strpos($url0, "http://") == false) OR (strpos($url0, "https://") == false) AND strpos($url0, "www") == false ){
         $url0 = "https://www." . $url0;    
        }
        else if (strpos($url0, "www") != false ){
        }
        else {
         $url0 = "https://" . $url0;
        }
    }

2 个答案:

答案 0 :(得分:2)

你可以试试像这样的正则表达式

$str = preg_replace('~^(?:\w+://)?(?:www\.)?~', "https://www.", $str);

它将替换任何协议和/或www.https://www.或如果不存在则添加。

  • ^匹配字符串的开头,(?:启动非捕获组。
  • (?:\w+://)?可选协议(\w+匹配一个或多个字词[A-Za-z0-9_]
  • (?:www\.)?可选文字www.

See demo and more explanation at regex101

答案 1 :(得分:2)

您可以使用parse_url功能检查网址格式:

<?php
$url = parse_url($url0);

// When https is not set, enforce it
if (!array_key_exists('scheme', $url) || $url['scheme'] !== 'https') {
    $scheme = 'https';
} else {
    $scheme = $url['scheme'];
}

// When www. prefix is not set, enforce it
if (substr($url['host'], 0, 4) !== 'www.') {
    $host = 'www.' . $url['host'];
} else {
    $host = $url['host'];
}

// Then set/echo this in your desired format
echo sprintf('%s://%s', $scheme, $host);

这应该可以节省您(以及将来需要处理此脚本的任何人)的一些正则表达式令人头痛的问题,同时也可以使代码更具可读性。

相关问题