本文介绍了正则表达式确定是否使用IPv6或IPv4以及是否提供了端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在搜索一个正则表达式,可以确定给定的 IP地址是 IPv4
还是 IPv6
和(对于我)是否连接了端口号.
I'm searching for a regular expression that can determine, if the given IP address is IPv4
or IPv6
and (most important for me) if a port number is attached, or not.
我尝试了一些正则表达式,但没有一个能按预期工作.
I tried a few regular expressions, but none of them worked as expected.
推荐答案
如果我可以假定输入将是一个简单的有效IP地址,而您只是想知道您是否具有端口,则可以执行以下操作:
If I can assume that the input will be a simple valid IP address and you simply want to know whether you have a port or not, you could do the following:
if (preg_match("/^(?:[0-9.]+|(?:\[[0-9a-fA-F:]+\]))(:[0-9]+)$/", $ip))
{
echo "A port was found.";
}
else
{
echo "A port was not found.";
}
这将与
-
[2001:0db8:85a3:08d3:1319:8a2e:0370:7344]:8080
或 -
127.0.0.1:8080
但不匹配
-
2001:0db8:85a3:08d3:1319:8a2e:0370:7344
或 -
127.0.0.1
请记住,该标准将定义为通过将IP文字括在方括号中来区分.
Keep in mind that the standard defines an IPv6 host to be distinguished by enclosing the IP literal within square brackets.
这篇关于正则表达式确定是否使用IPv6或IPv4以及是否提供了端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!