This example will show how to validate an IP Address to see if it is valid by using PHP Regular Expression.
First, you may need to know what an IP Address is consist of. An IP Address consists of 4 parts. Each part separated by period “.” and these part consists the digits which ranges from 0 to 255.
And this is a PHP function to validate IP Address by using Regular Expression:
<?php function validateIpAddress($ip_addr) { //first of all the format of the ip address is matched if(preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$ip_addr)) { //now all the intger values are separated $parts=explode(".",$ip_addr); //now we need to check each part can range from 0-255 foreach($parts as $ip_parts) { if(intval($ip_parts)>255 || intval($ip_parts)<0) return false; //if number is not within range of 0-255 } return true; } else return false; //if format of ip address doesn't matches } ?> |
Example:
<?php validateIpAddress("192.168.1.99"); // return true validateIpAddress("192.168.199"); // return false validateIpAddress("Regular Expression"); // return false ?> |