PHP has bulit-in mechanism to validate some common types, for your case it would be:
$isIP = filter_var($ip, FILTER_VALIDATE_IP);
$isSubnet = !filter_var($ip, FILTER_VALIDATE_IP,
FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
);
return $isIP && $isSubnet;
You can use FILTER_FLAG_IPV4/6
in first check as third parameter to ensure desired format.