天使漫步IT工作室天使漫步IT工作室

正确匹配URL的正则表达式(含多重子域名)


Warning: count(): Parameter must be an array or an object that implements Countable in /www/wwwroot/u11u.com/usr/themes/wq/functions.php on line 110

Warning: count(): Parameter must be an array or an object that implements Countable in /www/wwwroot/u11u.com/usr/themes/wq/functions.php on line 116

昨晚同事跟我说今天线上的正则匹配url上出了问题,在匹配多个子域名和无http或者https的时候匹配不上,如域名:open.weixin.qq.com 和 www.baidu.com 使用网上的一些正则就无法匹配。经过对网上给出的正则[a-zA-z]+://[^\s]*进行修改,经过测试后可以正确表达经过测试的多个情况。正则如下:

[a-zA-z]+(://)*[^\s]*

已经验证的url如下:

上面的情况应该涵盖了部分的url情形。测试平台参考:在线正则表达式测试

另外几个版本,同事说不能匹配多重子域名的情况,不加以验证。

  • (https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]
  • 摘自微软MSDN:(ht|f)tp(s?)://0-9a-zA-Z(:(0-9))(/?)([a-zA-Z0-9-.?,'/\+&%$#_])? (带参数的匹配有问题。)
  • http://([w-]+.)+[w-]+(/[w- ./?%&=]*)? (有严重的汉字问题。)

以上这些表达式摘自网页,可用当做学习参考。

本站原创,欢迎转载,转载敬请标明出处:天使漫步IT工作室 » 正确匹配URL的正则表达式(含多重子域名)
添加新评论


Warning: Use of undefined constant php - assumed 'php' (this will throw an Error in a future version of PHP) in /www/wwwroot/u11u.com/usr/themes/wq/comments.php on line 38