简体   繁体   中英

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

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

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