manishk
manishk

Reputation: 536

Regex to match Sub-domain of a Domain

The base url to match is- http://testdomain.com.

The condition to fulfill is- url "could" contain a subdomain from 3 to 10 characters length, for example: http://sub.testdomain.com

I have this right now-

$string = 'http://testdomain.com';
if(preg_match('/^(http):\/\/(([a-z]{3,10})?[\.])?(testdomain.com)/i', $string)) {
      echo 'Good';
} else {
     echo 'Bad';
}

The above condition matches http://.testdomain.com as well, which would be incorrect.

So the subdomain ('sub' in http://sub.testdomain.com), if present, should be 3 to 10 characters length and followed by a . and then testdomain.com

Upvotes: 0

Views: 123

Answers (1)

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

How about making the whole sub-domain portion optional with zero or multiple match using *. This will match both normal domain and sub-domain but not with a standalone . character for subdomain part. SEE

https?:\/\/([a-z0-9]+[.])*testdomain[.]com

$re = '/https?:\/\/([a-z0-9]+[.])*testdomain[.]com/i';
$str = ' http://testdomain.com
http://.testdomain.com
http://sub.testdomain.com';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

// Print the entire match result
var_dump($matches);

Upvotes: 1

Related Questions