Ip address validation in PHP using regular expression
Posted on April 18, 2008
Filed Under php, tutorial
If you don’t know how to validate the IP address format in PHP, then you are in the right place.I’ll show you here how to validate the IP address using regular expression in PHP.
As you guyz know, IP address consists four parts. Each parts separated by period “.” and these part consists the digits which ranges from 0 to 255.
Function to validate IP address in PHP using Regular Expression
//function to validate ip address format in php by Roshan Bhattarai(http://roshanbh.com.np)
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
}
As you can see above, first of all the format of the “$ip_addr” is validated using regular expression. In the regular expression “\d{1,3}” means that there should be digits which can be either 1 to 3 digits because a IP Adress can be “222.0.123.12″ or
“12.15.123.5″. So, each part can consists 1 to 3 digits.
After validating the format using regular expression, each part of the IP address is separated using period(”.”) using explode() function available in PHP. And finally, it is checked that each part of the IP address is between 0 to 225 or not.
Popularity: 10% [?]
If you like this post then please subscribe to my full RSS feed . You can also subscribe by email and have new posts sent directly to your inbox.And, You can also follow me on twitter at http://twitter.com/roshanbh.
Related Posts
» Email address validation in PHP
» Getting real IP address in PHP
» Getting country , city name from IP address in PHP
» Php function to validate two decimal places of a number
Comments
3 Responses to “Ip address validation in PHP using regular expression”
Leave a Reply





can you not simply use a regexp of: -
^[0-255]\.[0-255]\.[0-255]\.[0-255]$
i.e. four integers in the range of 0 to 255 with a period separating them?
It won’t work…try it…it will just validate a number like 0,1,2 or 5 only since it is equivalent to character set [0125]
Or you could do the whole kit+kaboodle in one regexp like so:
return preg_match(”/^((\d{1,2}|[01]\d{2}|2([0-4]\d|5[0-5]))\.){3}(\d{1,2}|[01]\d{2}|2([0-4]\d|5[0-5]))$/”,$ip_addr))