1 Star 0 Fork 0

平凡亦是收获/数据结构和算法

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
验证 IP 地址.php 2.41 KB
一键复制 编辑 原始数据 按行查看 历史
liuzeming 提交于 2021-01-09 21:58 +08:00 . add
<?php
// https://leetcode-cn.com/problems/validate-ip-address/solution/yan-zheng-ip-di-zhi-by-leetcode/
class Solution {
public function validateIPv4($IP)
{
// 以.为分隔符拆分
$nums = explode('.', $IP);
foreach ($nums as $x) {
// Validate integer in range (0, 255):
// 1. length of chunk is between 1 and 3
// 校验每一部分长度为1到3
if (strlen($x) == 0 || strlen($x) > 3) {
return "Neither";
}
// 2. no extra leading zeros
// 以0开头开始的 只能够长度为1 0.0.0.0 不能为192.01.2.1这种
if (strpos($x, '0') === 0 && strlen($x) != 1) {
return "Neither";
}
// 3. only digits are allowed
// 验证每个字符是否为数字
foreach (str_split($x, 1) as $ch) {
if (! is_numeric($ch)) {
return "Neither";
}
}
// 4. less than 255
// 是否超过255
if (intval($x) > 255) {
return "Neither";
}
}
return "IPv4";
}
public function validateIPv6($IP)
{
// 以:为分隔符拆分
$nums = explode(':', $IP);
// 允许的字符表
$hexdigits = array(
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f',
'A', 'B', 'C', 'D', 'E', 'F'
);
foreach ($nums as $x) {
// Validate hexadecimal in range (0, 2**16):
// 1. at least one and not more than 4 hexdigits in one
// 校验每一部分长度为1到4
if (strlen($x) == 0 || strlen($x) > 4) {
return "Neither";
}
// 2. only hexdigits are allowed: 0-9, a-f, A-F
// 校验字符是否在允许的字符表中
foreach (str_split($x, 1) as $ch) {
if (! in_array($ch, $hexdigits, true)) {
return "Neither";
}
}
}
return "IPv6";
}
public function validIPAddress($IP) {
if (count(explode('.', $IP)) == 4) {
return $this->validateIPv4($IP);
}
if (count(explode(':', $IP)) == 8) {
return $this->validateIPv6($IP);
}
return "Neither";
}
}
var_dump((new Solution())->validIPAddress("2001:0db8:85a3:0:0:8A2E:0370:7334"));
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/lzmcode/data-structure-and-algorithm.git
git@gitee.com:lzmcode/data-structure-and-algorithm.git
lzmcode
data-structure-and-algorithm
数据结构和算法
master

搜索帮助