Skip to content

Instantly share code, notes, and snippets.

@lbvf50mobile
Last active August 29, 2020 16:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lbvf50mobile/0db5289dee0874b2f159ebc1f2616a88 to your computer and use it in GitHub Desktop.
Save lbvf50mobile/0db5289dee0874b2f159ebc1f2616a88 to your computer and use it in GitHub Desktop.
Just PHP FUN 089.
<?php
# https://www.codewars.com/kata/515decfd9dcfc23bb6000006 IP Validation.
# Updatd solution from https://www.codewars.com/users/eremin
# Nice solution. But \d{1,2} will match 01 but in the description this is an invalid value for an octet:
# Note that leading zeros (e.g. 01.02.03.04) are considered invalid.
# To avoid leading zero I changed solution a little bit add one digit case, and range from 1 till 9 with digit \d|[1-9]\d.
function isValidIP(string $str): bool
{
$r = '(\d|[1-9]\d|1\d{2}|2([0-4]\d|5[0-5]))';
return (bool)preg_match("/^$r\.$r\.$r\.$r\$/", $str);
}
<?php
# https://www.codewars.com/kata/515decfd9dcfc23bb6000006 IP Validation.
function isValidIP(string $str): bool
{
echo "Input: $str \n";
$x = explode(".",$str);
if(4 != count($x)) return false;
foreach($x as $s){
if('0' == $s) continue;
if(! preg_match('/^[0-9]+$/',$s)) return false;
if('0' == $s[0]) return false;
if(255 < intval($s)) return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment