Friday, February 24, 2012

Validate an IP Address ( PCRE )

/*
 Validation footprint:
 - First part must be > 0.

 - All parts will be <= 255.
 - No 0.0.0.0 match
 - 00, 000 are not allowed in pairs if
   first digit starts with 0. allowed for
   > 0 first digit.

 
Valid examples:
 - 12.255.99.2
 
- 115.92.255.66
 - 127.2.1.66:2082
 ...
*/

/**
 * Validate the MySQL Timestamp
 *
 * @author   Junaid Atari <mj.atari@gmail.com>
 * @version  1.0
 * @see      http://codesnap.blogspot.com/
 * @param    string  $ip   IP to validate
 * @return   bool    TRUE on valid | FALSE
 */

function isValidIp $ip )
{
    
/* PCRE Pattern written by Junaid Atari */
    
return !preg_match '/^([1-9]\d|1\d{0,2}|2[0-5]{2})\.('.
                         
'(0|1?\d{0,2}|2[0-5]{2})\.){2}(0|1?'.
                         
'\d{0,2}|2[0-5]{2})(\:\d{2,4})?$/',
                         (string) 
$ip )
            ? 
false
            
true;
}

/*
 +-----------+
 |  Example  |
 +-----------+
*/

var_dump isValidIp '127.0.0.1:8080' ) );

/*
 +-----------+
 |  Output   |
 +-----------+
*/

# Output: True

0 comments:

Post a Comment