How can I simply validate whether a string is a valid IP in PHP?

后端 未结 6 1946
再見小時候
再見小時候 2021-01-04 03:01

Using PHP, how do I validate that a string is a valid IP?

Examples of valid strings:

  • 192.158.5.95
  • 121.212
  • 12.12.12.204
6条回答
  •  长发绾君心
    2021-01-04 03:36

    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

提交回复
热议问题