简体   繁体   中英

Checking to see if a URL is Google

I want to check a URL to see if it is a Google url or not.

I've got this function

function isValidURL($url)
{
    return preg_match('|^http(s)?://google.com|i', $url);
}

If i try

if ( isValidURL('http://google.com/') ){
    echo 'yes its google url';
}

It works fine. But if I try

if ( isValidURL('http://www.google.com/') ){
    echo 'yes its google url';
}

(with www ) I get an error!

Sure, because your regular expression is not ready to handle www.

Try

function isValidURL($url)
{
    return preg_match('|^http(s)?://(www\.)?google\.com|i', $url);
}

如果您要支持googles子网域,请尝试:

preg_match('/^https?:\/\/(.+\.)*google\.com(\/.*)?$/is', $url)

I like to use PHP's parse_url function to analyse url's. It returns an array with each part of the URL. This way you can be sure you're checking the correct part and it won't be thrown by https or query strings.

function isValidUrl($url, $domain_to_check){
       $url = parse_url($url);
       if (strstr($url['host'], $domain_to_search))
            return TRUE;
       return FALSE;
    }

Usage:

isValidUrl("http://www.google.com/q=google.com", "google.com");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM