Skip to content

Commit 25b7318

Browse files
committed
add is_ipv4 and is_ipv6 methods
1 parent 3738816 commit 25b7318

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

src/PhpStringHelpers.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -384,3 +384,17 @@ function is_slug(string $slug): bool
384384
return strHelpers::is_slug($slug);
385385
}
386386
}
387+
388+
if (!function_exists('is_ipv4')) {
389+
function is_ipv4(string $ip): bool
390+
{
391+
return strHelpers::is_ipv4($ip);
392+
}
393+
}
394+
395+
if (!function_exists('is_ipv6')) {
396+
function is_ipv6(string $ip): bool
397+
{
398+
return strHelpers::is_ipv6($ip);
399+
}
400+
}

src/utility/StrUtility.php

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -799,4 +799,42 @@ public function is_slug(string $slug): bool
799799
return false;
800800
return true;
801801
}
802+
803+
/**
804+
* find whether the type of a given ip is valid ipv4
805+
*
806+
* @param string $ip
807+
* @return boolean
808+
*/
809+
public function is_ipv4(string $ip): bool
810+
{
811+
if (empty($ip) || !is_string($ip))
812+
return false;
813+
814+
$pattern = '/^(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.(?!$)|$)){4}$/';
815+
816+
if (!preg_match($pattern, trim($ip)))
817+
return false;
818+
return true;
819+
}
820+
821+
/**
822+
* find whether the type of a given ip is valid ipv6
823+
*
824+
* @param string $ip
825+
* @return boolean
826+
*/
827+
public function is_ipv6(string $ip): bool
828+
{
829+
if (empty($ip) || !is_string($ip))
830+
return false;
831+
832+
$pattern = '
833+
(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))
834+
';
835+
836+
if (!preg_match($pattern, trim($ip)))
837+
return false;
838+
return true;
839+
}
802840
}

0 commit comments

Comments
 (0)