Skip to content

Instantly share code, notes, and snippets.

@phenomax
Created June 5, 2016 08:30
Show Gist options
  • Save phenomax/50eaa09cf46c1da8d98b10d6a1858a54 to your computer and use it in GitHub Desktop.
Save phenomax/50eaa09cf46c1da8d98b10d6a1858a54 to your computer and use it in GitHub Desktop.
A simple PHP IPv4 regex checker, including an optional solution
/**
* @param $str the string to check
* @return bool whether the String $str is a valid ip or not
*/
function isValidIP($str)
{
/**
* Alternative solution using filter_var
*
* return (bool)filter_var($str, FILTER_VALIDATE_IP);
*/
/**
* Normally preg_match returns "1" when there is a match between the pattern and the provided $str.
* By casting it to (bool), we ensure that our result is a boolean.
* This regex should validate every IPv4 addresses, which is no local adress (e.g. 127.0.0.1 or 192.168.2.1).
* This pattern was debugged using https://regex101.com/
*/
return (bool)preg_match('^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$', $str);
}
@ramonfincken
Copy link

    $this->data['ipv4'] = ( filter_var( $this->data['ip'], FILTER_VALIDATE_IP,FILTER_FLAG_IPV4) ) ? 1 : 0;
    $this->data['ipv6'] = ( filter_var( $this->data['ip'], FILTER_VALIDATE_IP,FILTER_FLAG_IPV6) ) ? 1 : 0;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment