添加https://protocol和www子域来输入url,如果它们没有';t退出


Add https:// protocol and www subdomain to input url if they doesn't exit?

我有一个接受URL输入的表单。我想要以下格式的URL,无论输入的格式是什么。

https://www.example.com

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

example.com

http://example.com

https://example.com

http://www.example.com

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

以下是我尝试过但没有成功的事情。

//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;
        }
    }

您可以尝试类似的正则表达式

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

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

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

请参阅regex101 上的演示和更多解释

您可以使用parse_url函数检查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);

这将为您(以及将来必须使用此脚本的任何人)省去一些正则表达式的麻烦,并使代码更具可读性。