使用 PHP 扩展 IPv6 地址的快速方法
我正在从事一个需要扩展 IPv6 地址的项目.其他用户创建的功能并不多,而且存在的功能都很丑陋.其中一些包括多个 foreach
和 gmp_init
,这增加了很多开销并且难以维护代码.我需要一个简单的、无负担的脚本来扩展 IPv6.
I was working on a project where I needed to expand IPv6 addresses. There are not many functions out there created by other users, and the ones that exist are ugly. Some of them included multiple foreach
's and gmp_init
, which added a lot of overhead and harder to maintain code. I need a simple, non-taxing script to expand IPv6.
为社区发布此内容.
推荐答案
以下是两行,其中 $ip
是一个精简的 IPv6 地址.返回扩展的 $ip
.
The following is a two liner, where $ip
is a condensed IPv6 address. Returns expanded $ip
.
示例:
$ip = "fe80:01::af0";
echo expand($ip); // fe80:0001:0000:0000:0000:0000:0000:0af0
功能:
function expand($ip){
$hex = unpack("H*hex", inet_pton($ip));
$ip = substr(preg_replace("/([A-f0-9]{4})/", "$1:", $hex['hex']), 0, -1);
return $ip;
}
相关文章