dskld5423 2015-12-04 23:05
浏览 69
已采纳

正则表达式使用通配符验证域

I am working on a DNS panel in PHP and I have to validate a DNS record name without the trailing dot. Here are a few examples:

example.com - match
sub.example.com - match
sub.sub.example.com - match
*.example.com - match
*.sub.example.com - match
sub.*.example.com - no mach
sub*.example.com - no match
*sub.example.com - no match

I am currently using this regex but the problem is it won't match a wildcard (*):

^(?!\-)(?:[a-z\d\-]{0,62}[a-z\d]\.){1,126}(?!\d+)[a-z\d]{1,63}$

I am not so good in formating regex. What is the best way to achieve this? Thanks!

  • 写回答

1条回答 默认 最新

  • dongmei8760 2015-12-05 09:59
    关注

    I found a solution using regex that doesn't fully respect domain rules but it works good enough, so if you are planning on using it I would suggest to do additional checks:

    ^(\*\.)?([a-z\d][a-z\d-]*[a-z\d]\.)+[a-z]+$
    

    There is a better way of solving this through PHP:

    $tmp = $domain_to_check;
    if(strpos($tmp, '*.') === 0){
        $tmp = substr($tmp, 2);
    }
    
    if(filter_var('http://' . $tmp, FILTER_VALIDATE_URL)){
        // The format is valid
    }else{
        // The format is invalid
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)