doumengwei0138 2017-10-05 07:41
浏览 22
已采纳

验证非英语域名[重复]

This question already has an answer here:

Example domain: http://мппм.рф

After converting domain into ASCII, it become: Xn--l1aaia.xn--p1ai

But my existing PHP function to valid domain returns false.

Existing function to validate domain

function ValidateDomain($domain)
{
    if(!preg_match("/^([-a-z0-9]{2,100})\.([a-z\.]{2,24})$/i", $domain))
    {
        return false;
    }
    return $domain;
}

I have tried the following one to validate domain

if( !preg_match('/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $domain) )
</div>
  • 写回答

1条回答 默认 最新

  • duanpiyao2734 2017-10-05 07:55
    关注

    I think that мппм.рф is already in UTF8, so forcing a conversion will not help. Your regular expression is quite simple, and can be replace by something like this:

    function validateDomain($domain)
    {
      $parts     = explode('.',$domain);
      $name      = array_shift($parts);
      $extension = implode('.',$parts);
      if ((strlen($name) >= 2) && (strlen($name) <= 100) && 
          (strlen($extension) >= 2) && (strlen($extension) <= 24)) return $domain;
      else return FALSE;      
    }
    

    It will work the same, but also for non-a-z characters, and it is easier to understand than when it uses a regular expression. You can make it slightly more compact and efficient by doing this:

    function validateDomain($domain)
    {
      $parts   = explode('.',$domain);
      $nameLen = strlen(array_shift($parts));
      $extLen  = strlen(implode('.',$parts));
      if( ($nameLen >= 2) && ($nameLen <= 100) && 
          ($extLen >= 2) && ($extLen <= 24) ) return $domain;
      else return FALSE;      
    }
    

    You could also use the multibyte string functions like this:

    function validateDomain($domain)
    {
      $point   = mb_strpos($domain,'.');
      $nameLen = mb_strlen(mb_substr($domain,0,$point));
      $extLen  = mb_strlen(mb_substr($domain,$point+1));
      if( ($nameLen >= 2) && ($nameLen <= 100) && 
          ($extLen >= 2) && ($extLen <= 24) ) return $domain;
      else return FALSE;      
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示