tags:

views:

110

answers:

5

Hi,

How to add http:// to the url if there isn't a http:// or 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
A: 

Try this. Not watertight*, but might be good enough:

function addhttp($url) {
    if (!preg_match("@^[hf]tt?ps?://@", $url)) {
        $url = "http://" . $url;
    }
    return $url;
}

*: that is, prefixes like "fttps://" are treated as valid.

nickf
This would match (ergo return true and if would evaluate to false) weird combinations.. like htps, fttps, fttp, htp, I guess.
msakr
@mahmoudsakr you're right
David
@mahmoudsakr - in either case, you're not going to get a valid url (eg: `http://fttps://google.com`), so I wouldn't be too worried about it.
nickf
A: 

nickf solution modified:

function addhttp($url) {
    if (!preg_match("@^https?://@i", $url) && !preg_match("@^ftps?://@i", $url)) {
        $url = "http://" . $url;
    }
    return $url;
}
msakr
I believe `ftps://` is also valid.
Alix Axel
@Alix: wasn't aware of that. Edited.
msakr
+1  A: 

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.

Alix Axel
David
@David: No problem, you're welcome.
Alix Axel
+1  A: 

Scan the string for ://, if it does not have it, prepend http:// to the string.., everything else just use the string as is.

This will work unless you have rubbish input string.

Rosdi
i'de prefer a regex version :)
David
Don't be too quick on regex. Regex tends to be hard to read and it could introduce another problem/bug once the problem grows.
Rosdi
+2  A: 

Simply check if there is a protocol (delineated by "://") and add "http://" if there isn't.

if (false === strpos($url, '://')) {
    $url = 'http://' . $url;
}
Brenton Alker
+1 for being the most readable solution of all. The programmer's intent is quickly understood at a glance.
Rosdi