PHP正则表达式,用于验证URL [英] PHP regex for validating a URL
问题描述
我正在寻找一个合适的正则表达式来匹配URL(具有方案,域,路径等的完整URL) 我通常会使用filter_var,但是在这种情况下我将无法使用,因为我必须支持PHP< 5.2!
I'm looking for a decent regex to match a URL (a full URL with scheme, domain, path etc.) I would normally use filter_var but I can't in this case as I have to support PHP<5.2!
我已经在网上搜索过,但是找不到任何我相信会很简单的东西,所以我在SO上只能找到有人说要使用filter_var.
I've searched the web but can't find anything that I'm confident will be fool-proof, and all I can find on SO is people saying to use filter_var.
有人为此使用正则表达式吗?
Does anybody have a regex that they use for this?
我的代码(只是为了您可以看到我要实现的目标):
My code (just so you can see what I'm trying to achieve):
function validate_url($url){
if (function_exists('filter_var')){
return filter_var($url, FILTER_VALIDATE_URL);
}
return preg_match(REGEX_HERE, $url);
}
推荐答案
You could try this one. I haven't tried it myself but it's surely the biggest regexp I've ever seen, haha.
^(?#Protocol)(?:(?:ht|f)tp(?:s?)\:\/\/|~\/|\/)?(?#Username:Password)(?:\w+:\w+@)?(?#Subdomains)(?:(?:[-\w]+\.)+(?#TopLevel Domains)(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|travel|[a-z]{2}))(?#Port)(?::[\d]{1,5})?(?#Directories)(?:(?:(?:\/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|\/)+|\?|#)?(?#Query)(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*(?#Anchor)(?:#(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)?$
这篇关于PHP正则表达式,用于验证URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!