Ari
Ari

Reputation: 4969

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?

Upvotes: 2

Views: 1434

Answers (4)

CodeAngry
CodeAngry

Reputation: 12985

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\.-]*\.[a-z]+$~i', $); or write a proper function that checks against consecutive dots, proper gtld, verifies lengths and more.

Upvotes: 2

Sabuj Hassan
Sabuj Hassan

Reputation: 39365

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

Upvotes: 0

Daniel W.
Daniel W.

Reputation: 32290

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

Upvotes: 2

Jorge Faianca
Jorge Faianca

Reputation: 791

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

Upvotes: 0

Related Questions