Created
June 5, 2016 08:30
-
-
Save phenomax/50eaa09cf46c1da8d98b10d6a1858a54 to your computer and use it in GitHub Desktop.
A simple PHP IPv4 regex checker, including an optional solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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
commented
Jun 14, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment