简体   繁体   English

URL验证正则表达式

[英]URL Validation Regex

As far as i know there are many other questions similar to title, but my main reason for asking this question is i want my validation as perfect as i want. 据我所知,还有很多其他与标题类似的问题,但是我问这个问题的主要原因是我希望我的验证尽可能完美。 Here is my explanation which URL should valid 这是我的解释,哪个URL应该有效

http:// (if given then match otherwise skip), domain.com (should match & return validate) subdomain.domain.com (should match & return validate) www.com (should return false) http://www.com (should return false) http:// (如果提供,则匹配,否则跳过), domain.com (应匹配并返回验证) subdomain.domain.com (应匹配并返回验证) www.com (应返回false) http://www.com (应该返回false)

I searched a lot about perfect regex pattern according to my need but didn't succeed so thats why i made my self and posting here to want to know that anyother Valid URL would it skip or not except http://localhost . 我根据自己的需要搜索了很多关于完美正则表达式的内容,但没有成功,因此,我为什么要发表自己的看法,并在此处发布信息,以了解除http:// localhost之外,其他任何有效URL都会跳过还是不跳过。 If yes then please correct me. 如果是的话,请纠正我。

Pattern: 图案:

((?:http|https|ftp)://)?(?:www.)?((?!www)[A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(\\d+)?/? ((?:http | https | ftp)://)?(?:www。)?((?!www)[A-Z0-9] [A-Z0-9_-] *(?:。[A -Z0-9] [A-Z0-9 _-] *)+):?(\\ d +)?/?

I know this actually doesn't answer your question directly, but REGEXes aside, you can also use filter_var() , with the flag FILTER_VALIDATE_URL, which returns the URL in case of valid url, or FALSE otherwise: 我知道这实际上并不能直接回答您的问题,但是除了REGEX之外,您还可以使用带有标志FILTER_VALIDATE_URL的filter_var() ,如果URL有效,则返回URL,否则返回FALSE:

   var_dump(filter_var('http://example.com', FILTER_VALIDATE_URL));
   // string(18) http://example.com

You can read here the filters used by this function, especially the last row regarding flags used by the VALIDATE_URL filter. 您可以在此处阅读此功能使用的过滤器,尤其是有关VALIDATE_URL过滤器使用的标志的最后一行。

I actually don't know how it's implemented internally, but I suppose it works better than many regexes you can find outside in the wild internet. 我实际上不知道它是如何在内部实现的,但是我想它比在野外互联网中可以找到的许多正则表达式更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM