且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查 URL 时更改正则表达式以允许 IP 地址?

更新时间:2022-11-14 17:40:11

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

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);