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

后端 未结 6 1958
再見小時候
再見小時候 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:45

    Just in case there's anyone that doesn't want to use the ip2long function, here is a simple function (Idea taken from a class in osTicket):

    function is_ip( $ip = null ) {
    
        if( !$ip or strlen(trim($ip)) == 0){
            return false;
        }
    
        $ip=trim($ip);
        if(preg_match("/^[0-9]{1,3}(.[0-9]{1,3}){3}$/",$ip)) {
            foreach(explode(".", $ip) as $block)
                if($block<0 || $block>255 )
                    return false;
            return true;
        }
        return false;
    }
    

提交回复
热议问题