检查 URL 时更改正则表达式以允许 IP 地址? [英] Alter regex to allow IP address when checking URL?

查看:22
本文介绍了检查 URL 时更改正则表达式以允许 IP 地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下正则表达式来检查 URL 是否有效:

I have the following regex to check to see if a URL is valid:

preg_match('/^(http(s?):\/\/)?(www\.)?+[a-zA-Z0-9\.\-\_]+(\.[a-zA-Z]{2,3})+(\/[a-zA-Z0-9\_\-\s\.\/\?\%\#\&\=]*)?$/i', $url);

我喜欢修改这部分 [a-zA-Z0-9\.\-\_]+(\.[a-zA-Z]{2,3})(在至少我希望它是这个粗体部分)要么是一个 IP 地址,要么是这个突出显示的部分.

I like to modify this part [a-zA-Z0-9\.\-\_]+(\.[a-zA-Z]{2,3}) (at least I hope it is this bold part) to be either an IP address or this highlighted part.

目前,正则表达式对我来说非常好,因为它可以正确地找到错误的 URL——尽管我相信一旦 ICANN 的新域政策生效(即谷歌可能想要url http://search.google - 而不是 http://google.com 用于搜索)

At the moment, the regex is pretty good for me as it finds the bad URLs correctly - though I believe this will start failing to work correctly once the new domain policy from ICANN goes live (ie. Google may want to have the url http://search.google - instead of http://google.com for search)

无论如何,我想添加允许 IP 地址也是有效 URL 的功能,但我不确定如何将其纳入正则表达式

Anyhow, I'd like to add the ability to allow IP addresses to also be a valid URL, but I'm unsure how to factor that into the regex

如果有人能伸出援手,那就太好了!

If anyone could lend a hand, then that would be great!

推荐答案

这个正则表达式似乎有效:

This regex seems to work:

^(http(s?):\/\/)?(((www\.)?+[a-zA-Z0-9\.\-\_]+(\.[a-zA-Z]{2,3})+)|(\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b))(\/[a-zA-Z0-9\_\-\s\.\/\?\%\#\&\=]*)?$

在检查http"之后的部分,它只是执行 OR 操作,以匹配域名或 IP.以下是相关摘录:

At the section after the check for "http", it simply performs an OR operation, to match either a domain name, or IP. Here is the relevant excerpt:

((www\.)?+[a-zA-Z0-9\.\-\_]+(\.[a-zA-Z]{2,3})+)|(\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b)

IP 表达式有点长,但它确保它是一个有效的 IP(例如,不是 999.999.999.999).您可以轻松地将其替换为另一个 IP 检查.

The IP expression is somewhat long, but it makes sure that it is a valid IP (as in, not 999.999.999.999). You can easily substitute it for another IP check.

此处已将其合并到您之前的代码中:

Here it is incorporated into your earlier code:

preg_match('/^(http(s?):\/\/)?(((www\.)?+[a-zA-Z0-9\.\-\_]+(\.[a-zA-Z]{2,3})+)|(\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b))(\/[a-zA-Z0-9\_\-\s\.\/\?\%\#\&\=]*)?$/i', $url);

这篇关于检查 URL 时更改正则表达式以允许 IP 地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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