开发者

Add http:// to the beginning of submitted url

开发者 https://www.devze.com 2023-02-25 13:11 出处:网络
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 use开发者_开发问答r type \"example.com\" s

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 use开发者_开发问答r 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:

  • substr()


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 :)


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消