正则表达式匹配域的子域

Regex to match Sub-domain of a Domain

要匹配的基 url 是- http://testdomain.com

满足条件是—— url "could" contain a subdomain from 3 to 10 characters length, for example: http://sub.testdomain.com

我现在有这个-

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

上述条件也符合 http://.testdomain.com,这是不正确的。

因此子域(http://sub.testdomain.com 中的'sub')如果存在,长度应为 3 到 10 个字符,后跟一个 .然后 testdomain.com

如何使用 * 使整个子域部分可选零或多个匹配。这将匹配普通域和子域,但不匹配子域部分的独立 . 字符。 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);