Check if string is ip subnet

ip, php, regex, subnet

Solution

<?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);

    }

}


    ?>

Problem

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?

Original source