将http://添加到提交的URL的开头

I am looking the best way to add http:// to a submitted url. I have a site that allows users to submit their website url when signing up, the problem is some user type "example.com" some users type "www.example.com" and some type "http(s)://example.com"

What I would like to accomplish is to make sure the end result is "http(s)://example.com" regardless of what they submit.

Is there any way to do this and still account for other things like co.uk or https?

You don't really need of REGEX. REGEX are often a lot expensive. Here's a home made function that achieve your goal:

function fix_url($url) {
    return (substr($url, 0, 7) == 'http://' || substr($url, 0, 8) == 'https://')
        ? $url 
        : 'http://'.$url;
}

Samples:

$url = 'example.com';
$url1 = 'httpexample.com';
$url2 = 'http://example.com';
$url3 = 'https://example.com';

echo fix_url($url);
echo '<br>';
echo fix_url($url1);
echo '<br>';
echo fix_url($url2);
echo '<br>';
echo fix_url($url3);
echo '<br>';

Output:

http://example.com
http://httpexample.com
http://example.com
https://example.com

If you have any doubt, please consider adding a comment below.

References:

To account for http(s)://, this is very straight forward since there are two options only to check. i.e. check that the link starts with "http://" or "https://", if not then add "http://".

The other part of your question which is to account for ".co.uk", you can either gather all available suffixes in a dictionary which is a very bad idea or you can simply check for the presence of a "." leaving what comes after the "." to the user's responsibility.

I hope I answered your question :)

Search for 'http' and 'https' in the submitted URL, if search returned null add 'http' to the beginning. With Javascript: var mystring="example.com"; var normal=-1; var secured=-1; normal=mystring.search(/http/i); secured=mystring.search(/https/i); and so on

for php,

$str = preg_replace('/(?m)^(?!https?:\/\/.+)(\S+)/',"http://$1",$str);

Easy way to fix your URL :)

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

    return $url;
}