检查字符串是否在PHP中包含IPV6地址 [英] Check if a string contains an IPV6 address in PHP

查看:68
本文介绍了检查字符串是否在PHP中包含IPV6地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用PHP,我需要检查字符串是否包含IPv6地址-如果存在,则提取该IPv6地址.

Using PHP, I need to check if a string contains an IPv6 address - and then extract that IPv6 address if it does.

如果正好是IPv6,我有一个正则表达式与字符串匹配:

I've got a regex that is matching a string if it's exactly an IPv6:

$matches = [];
$regex = '/^(((?=.*(::))(?!.*\3.+\3))\3?|([\dA-F]{1,4}(\3|:\b|$)|\2))(?4){5}((?4){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})\z/i';
preg_match($regex, $ipv6, $matches);

我遇到的问题是能够在任一侧添加通配符,因此我可以匹配以下内容:

What I'm stuck with is being able to add a wildcard on either side, so I can match things like:

  • http://2001:0db8:85a3:0000:0000:8a2e:0370:7334/something/page.html
  • http://2001:0db8:85a3:0000:0000:8a2e:0370:7334
  • 2001:0db8:85a3:0000:0000:8a2e:0370:7334/something/page.html

最终我需要这样做,以便将方括号括在IPv6地址周围,因此它符合RFC 3986(例如http://[2001:0db8:85a3:0000:0000:8a2e:0370:7334]/something/page.html).

Ultimately I need to do this so I can wrap square brackets around an IPv6 address, so it conforms to RFC 3986 (e.g http://[2001:0db8:85a3:0000:0000:8a2e:0370:7334]/something/page.html).

推荐答案

为了验证字符串是否为有效的IPv6地址,您无需阅读和理解regex. PHP函数 filter_var() 可以为您完成繁重的工作:

You don't need difficult to read and understand regex in order to verify if a string is a valid IPv6 address. The PHP function filter_var() can do the heavylifting for you:

echo(filter_var('2001:0db8:85a3:0000:0000:8a2e:0370:7334', FILTER_VALIDATE_IP));
# 2001:0db8:85a3:0000:0000:8a2e:0370:7334

echo(filter_var('2001:0db8:85a3::8a2e:0370:7334', FILTER_VALIDATE_IP));
# 2001:0db8:85a3::8a2e:0370:7334

echo(filter_var('192.168.0.1', FILTER_VALIDATE_IP));
# 192.168.0.1

var_dump(filter_var('192.168.0.1', FILTER_VALIDATE_IP, FILTER_FLAG_IPV6));
# bool(false)

如果输入值有效(根据作为第二个参数传递的过滤器和作为第三个参数传递的选项),则返回输入值,否则返回FALSE.

It returns the input value if it is valid (according to the filter passed as the second argument and the options passed as the third argument) or FALSE otherwise.

如果IP地址是URL的域,则PHP函数 parse_url() 可用于提取它:

If the IP address is the domain of an URL then the PHP function parse_url() can be used to extract it:

print_r(parse_url('http://2001:0db8:85a3:0000:0000:8a2e:0370:7334/something/page.html'));
# Array
# (
#     [scheme] => http
#     [host] => 2001:0db8:85a3:0000:0000:8a2e:0370:7334
#     [path] => /something/page.html
# )

示例中的最后一个字符串(2001:0db8:85a3:0000:0000:8a2e:0370:7334/something/page.html)不是URL.它只是一些随机文本,碰巧看起来像一个不完整(无效)的URL.我没有一个简单的解决方案:-(

The last string in your example (2001:0db8:85a3:0000:0000:8a2e:0370:7334/something/page.html) is not an URL. It is just some random text that happens to look like an incomplete (and invalid) URL. I don't have a simple solution for it :-(

这篇关于检查字符串是否在PHP中包含IPV6地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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