Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string is ip subnet

Tags:

regex

php

ip

subnet

I have list of ip addresses as string, but there are some subnets in that list too. For example:

... 127.0.0.1 (this is ip) 127.0.0.1/24 (this is subnet) ...

I want to check which is ip and which is subnet. So far I can filter ip but I couldn`t find a way to check subnet:

foreach ($ipstrings as $ip) {
        if(filter_var($ip, FILTER_VALIDATE_IP) !== false){
            $ips[] = $ip;
        }
        elseif (is_subnet) {
            $subnets[] = $ip;
        }
    }

How can make is_subnet work?

like image 531
Jamol Avatar asked Oct 23 '25 17:10

Jamol


1 Answers

<?php

// array of ip and subnets
$ipandmask = array('127.0.0.1','127.0.0.0','127.0.0.2','127.0.0.3/24','127.0.0.4/16'); 

foreach ($ipandmask as $ipmask) {

        if(preg_match('~^(?:[0-9]{1,3}\.){3}[0-9]{1,3}/[0-9][0-9]~',$ipmask,$subnet)){
        echo "</br>";
        echo "Subnet =>";
        print_r ($subnet);

    }

        if(preg_match('~^(?:[0-9]{1,3}\.){3}[0-9]{1,3}~',$ipmask,$ip)){
        echo "</br>";
        echo "Ip =>";
        print_r ($ip);

    }

}


    ?>
like image 89
user3227275 Avatar answered Oct 26 '25 09:10

user3227275



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!