简体   繁体   中英

php - Check Whether A given Value is A Domain or URL

How to check if a user given value is url or just domain?

Example:

    $a = array('http://domain.com/page/ex.html',
    'http://domain.com/',
    'domain.com'
    );

foreach ($a as $v) {

if ($v is url)
// do something
} elseif ($v is domain) {
// do another thing
}

}

What should I do to check whether $v value is url or domain?

Use filter_var($, FILTER_VALIDATE_URL) to test for URL. To test for domain you can either do a superficial error-prone regexp like preg_match('~^[a-z0-9][a-z0-9\\.-]*\\.[az]+$~i', $); or write a proper function that checks against consecutive dots, proper gtld, verifies lengths and more.

Use parse_url :

http://us.php.net/parse_url

foreach ($a as $v) {
   $url = parse_url($v);
   if (isset($url['host']) && $url['host'] != '') {
       // valid host
   }
}

Well, you should use a Regular Expession. Check this post from Daring Fireball

You can use regex,

Example: live

        $domainRegex = '/^[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$/';
        $urlRegex = '/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/';
        $a = array('http://domain.com/page/ex.html',
            'http://domain.com/',
            'domain.com'
        );

        foreach ($a as $v) {

            if (preg_match($urlRegex, $v)) {
                echo $v.': url<br/>';
            } else if (preg_match($domainRegex, $v)) {
                echo  $v.': domain<br/>';
            }
        }

Output should be:

http://domain.com/page/ex.html: url
http://domain.com/: url
domain.com: domain

Well, not sure what is your definition for domain and url. From the example, I guess if any string contains a / then its a URL.

if(preg_match("|/|i", $v)){
    print "url\n";
}

Without regex:

if(strpos($v, "/")){
    print "url\n";
}

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