/** * @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); }