用于验证 URL 的 PHP 正则表达式 [英] PHP regex for validating a URL

查看:63
本文介绍了用于验证 URL 的 PHP 正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个合适的正则表达式来匹配 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-fd]{2})+)+|/)+|?|#)?(?#Query)(?:(?:?(?:[-w~!$+|.,*:]|%[a-fd{2}])+=?(?:[-w~!$+|.,*:=]|%[a-fd]{2})*)(?:&(?:[-w~!$+|.,*:]|%[a-fd{2}])+=?(?:[-w~!$+|.,*:=]|%[a-fd]{2})*)*)*(?#Anchor)(?:#(?:[-w~!$+|.,*:=]|%[a-fd]{2})*)?$

这篇关于用于验证 URL 的 PHP 正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆