域名的简单正则表达式

时间:2011-10-12 14:50:58

标签: php regex dns

如何确保域名与这3个简单标准相匹配:

  • 以.com / .net
  • 结尾

不得以

开头
  • http://或https://
  • 的http:// WWW。或者https:// www。

我已经设法理解了与第一个标准相对应的正则表达式的这一部分:

/.*(\.com|\.net)$/

但我不知道如何实现另外两个条件来制作一个独特的正则表达式。

感谢您的帮助。

5 个答案:

答案 0 :(得分:4)

使用模式“不启动”有点棘手。

最明智的做法是两个独立的正则表达式,一个匹配你想要的,一个不匹配你不想要的。

但你可以在一个负面预测中执行此操作:

/^(?!https?:\/\/(www\.)?).*(\.com|\.net)$/

编辑:更正由ridgerunner

指出的断言

答案 1 :(得分:2)

如果您需要确保字符串不包含前两个点,为什么不简单地使用str_replace然后测试第一个标准?我认为这将更容易,也更有效率。

答案 2 :(得分:2)

正则表达式解决方案很简单。简单地在字符串的开头处断言负向前瞻,如下所示:(带注释......)

if (preg_match('%
    # Match non-http ,com or .net domain.
    ^             # Anchor to start of string.
    (?!           # Assert that this URL is NOT...
      https?://   # HTTP or HTTPS scheme with
      (?:www\.)?  # optional www. subdomain.
    )             # End negative lookahead.
    .*            # Match up to TLD.
    \.            # Last literal dot before TLD.
    (?:           # Group for TLD alternatives.
      net         # Either .net
    | com         # or .com.
    )             # End group of TLD alts.
    $             # Anchor to end of string.
    %xi', $text)) {
    // It matches.
} else {
    // It doesn't match.
}

请注意,由于:http://www.http://的子集,因此无需使用可选www.的表达式。这是一个较短的版本:

if (preg_match('%^(?!https?://).*\.(?:net|com)$%i', $text)) {
    // It matches.
} else {
    // It doesn't match.
}

简单的正则表达救援!

答案 3 :(得分:0)

^[a-zA-Z\.]+\.(com|net)$

这有用吗?

如果我理解你正确,你想检查一个字符串列表,并找出哪些是域名。 e.g。

http://www.a.b (F)
a.com (T)
b.net  (T)
https://google.com (F)

答案 4 :(得分:0)

试试这个:

if(preg_match('/^(?:http://|https://)(?:[w]{3}|)/i', $subject))
{
  echo 'Fail';
}
else
{
  if(preg_match('/(?:.*(\.com|\.net))$/i', $subject))
  {
    echo 'Pass';
  }
  else
  {
    echo 'Fail';
  }
}
相关问题