Search code examples
phpregex

How to add http:// if it doesn't exist in the URL


How can I add http:// to a URL if it doesn't already include a protocol (e.g. http://, https:// or ftp://)?

Example:

addhttp("google.com"); // http://google.com
addhttp("www.google.com"); // http://www.google.com
addhttp("google.com"); // http://google.com
addhttp("ftp://google.com"); // ftp://google.com
addhttp("https://google.com"); // https://google.com
addhttp("http://google.com"); // http://google.com
addhttp("rubbish"); // http://rubbish

Solution

  • A modified version of @nickf code:

    function addhttp($url) {
        if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
            $url = "http://" . $url;
        }
        return $url;
    }
    

    Recognizes ftp://, ftps://, http:// and https:// in a case insensitive way.