【问题标题】:php regex does domain string have www and top level domainphp regex 域字符串是否具有 www 和顶级域
【发布时间】:2011-06-03 06:54:42
【问题描述】:

在正则表达式方面我有点业余,但考虑到我有以下三个域

www.google.com
www.google.co.uk
google.com

我想创建一些正则表达式来测试该域是否具有www 以及.co.uk.com

有人知道一些可以测试这个的正则表达式吗?

【问题讨论】:

  • 你真的需要使用正则表达式吗?

标签: php regex string dns


【解决方案1】:

你不需要正则表达式,你可以使用 strpos 据说比正则表达式更快。

if ( strpos('www.', $mystring) !== false ) {
    //www was found in the string
} else {
    //www was not foun in the string
}

如果你真的想慢一点并使用正则表达式,你可以像这样测试所有这些

preg_match('/www|\.com|\.co\.uk/', $mystring);

例如,如果您想为 www 应用与 .com 不同的逻辑,您可以使用

preg_match('/www/', $string);
preg_match('/\.com/', $string);
preg_match('/\.co\.uk/', $string);

【讨论】:

    【解决方案2】:

    试试这个:

    /^www.*(?:com|co\.uk)$/
    

    【讨论】:

      【解决方案3】:

      根据我从您的问题中了解到的情况,域需要以 www 开头并以 .co.uk.com 结尾。所以这里是正则表达式:

      <?php
          $domains = array(
              "www.google.com",
              "www.google.co.uk",
              "google.com"
          );
          foreach($domains as $domain){
              echo sprintf(
                  "%20s -> %d\n",
                  $domain,
                  preg_match("@^www\\..+(\\.co\\.uk|\\.com)$@", $domain)
              );
          }
      ?>
      

      【讨论】:

        【解决方案4】:

        简单

        $ar = array();
        $t = array("www.google.com","www.google.co.uk","google.com","www.google");
        foreach ($t as $str) {
            if (preg_match('/^www\.(.*)(\.co.uk|\.com)$/',$str)) {
                echo "Matches\n";
            }
        }
        

        有条件的

        $ar = array();
        $t = array("www.google.com","www.google.co.uk","google.com","www.google");
        foreach ($t as $str) {
            switch (true) {
                case preg_match('/^www\.(.*)$/',$str) :
                // code
                case preg_match('/^(.*)(\.co.uk)$/',$str) :
                // code
                case preg_match('/^(.*)(\.com)$/',$str) :
                // code
                break;
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-12-14
          • 2011-11-16
          • 1970-01-01
          • 1970-01-01
          • 2012-06-05
          • 2017-02-05
          • 1970-01-01
          • 2018-01-11
          相关资源
          最近更新 更多