Using PHP, how do I validate that a string is a valid IP?
Examples of valid strings:
If @Tomgrohl brought up regexes, you can do it in one line:
function is_ip($ip) {
return is_string($ip) && preg_match('/^([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-5][0-5])\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-5][0-5])\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-5][0-5])\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-5][0-5])$/');
}
Explanation:
/ // regex delimiter
( // start grouping
[0-9] // matches from 0 to 9
| // or
[1-9][0-9] // matches from 10 to 99
| // or
1[0-9]{2} // matches from 100 to 199
| // or
2[0-5][0-5] // matches from 200 to 255
) stop grouping
\. // matches the dot
// the rest (same) of the numbers
/ regex delimiter
Online tester: https://regex101.com/r/eM4wB9/1
Note: it only matches ipv4