PHP function to validate IPv4 and IPv6 using regex

Edit

Please see Natxet's comment on this answer, and Morgon's answer for a better solution.

Original Answer

You can just use inet_pton. It returns false if the IP is not a valid IPv6 or IPv4:

function validateIP($ip){
    return inet_pton($ip) !== false;
}

try

//validates IPv4 and IPv6
$isValid = filter_var($ip, FILTER_VALIDATE_IP);

//validates IPv4
$isValid = filter_var($ip, FILTER_VALIDATE_IP,FILTER_FLAG_IPV4);

//validates IPv6
$isValid = filter_var($ip, FILTER_VALIDATE_IP,FILTER_FLAG_IPV6);

//validates IPv4 and IPv6, excluding reserved and private ranges
$isValid = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);

http://www.php.net/manual/en/filter.filters.validate.php


Check PHP's filter_var function. It has a number of validators, including IPv4 and IPv6.

$isValid = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
// $isValid can be evaluated as boolean, as it's FALSE if validation fails.

In addition to Morgon and Mark Pro Campos answers:

function is_valid_ip($ip='', $ip_type=''){

    $isValid=false;

    if($ip_type=='ipv4'){

        //validates IPV4
        $isValid = filter_var($ip, FILTER_VALIDATE_IP,FILTER_FLAG_IPV4);
    }
    elseif($ip_type=='ipv6'){

        //validates IPV6
        $isValid = filter_var($ip, FILTER_VALIDATE_IP,FILTER_FLAG_IPV6);
    }
    else{

        //validates IPV4 and IPV6
        $isValid = filter_var($ip, FILTER_VALIDATE_IP);
    }

    if($isValid == $ip){

        $isValid=true;
    }

    return $isValid;
}

Resources

http://php.net/manual/en/function.filter-var.php