- Email address validation:
function isEmail($email){
$regex = "/\w+@\w+.\w+/";
return preg_match($regex, $email);
} - URL validation:
function isURL($url){
$regex = "/(https?ftpfile):\/\/.\w+.\w\w+/";
return preg_match($regex, $url);
} - Validate IP:
function isIp($ip){
$block = "(25[012345]2[01234]\d[01]?\d\d?)";
$regex = "/^($block\.$block\.$block\.$block)$/";
return preg_match($regex, $ip);
} - Is MAC address:
function isMac($mac, $separator){
$mac = strtoupper($mac);
$block = "([A-F][A-F][A-F][0-9][0-9][A-F][0-9][0-9])";
$regex = "/^($block$separator$block$separator$block$separator$block$separator$block$separator$block)$/";
return preg_match($regex, $mac);
} - Is this a private IP:
function isPrivateIp($ip){
// 10.0.0.0 – 10.255.255.255
// 172.16.0.0 – 172.31.255.255
// 192.168.0.0 – 192.168.255.255
$block = "(25[012345]2[01234]\d[01]?\d\d?)";
$rangeA = "/^(10)\.($block)\.($block)\.($block)$/";
$rangeB = "/^(172)\.(3[01]2[0-9]1[6-9])\.($block)\.($block)$/";
$rangeC = "/^(192)\.(168)\.($block)\.($block)$/";
$regex = "/^($block\.$block\.$block\.$block)$/";
if (preg_match($rangeA, $ip))
return true;
else if (preg_match($rangeB, $ip))
return true;
else if (preg_match($rangeC, $ip))
return true;
else if (preg_match($regex, $ip))
return false;
else
return false;
} - Is it a class A private ip or B or C:
function getPrivateIpClass($ip){
// 10.0.0.0 – 10.255.255.255
// 172.16.0.0 – 172.31.255.255
// 192.168.0.0 – 192.168.255.255
$block = "(25[012345]2[01234]\d[01]?\d\d?)";
$rangeA = "/^(10)\.($block)\.($block)\.($block)$/";
$rangeB = "/^(172)\.(3[01]2[0-9]1[6-9])\.($block)\.($block)$/";
$rangeC = "/^(192)\.(168)\.($block)\.($block)$/";
$regex = "/^($block\.$block\.$block\.$block)$/";
if (preg_match($rangeA, $ip))
return "A";
else if (preg_match($rangeB, $ip))
return "B";
else if (preg_match($rangeC, $ip))
return "C";
else if (preg_match($regex, $ip))
return $ip." is not a private IP.";
else
return $ip." is not a valid IP.";
}
Thursday, February 5, 2009
Some useful PHP function (RegEx):
Subscribe to:
Post Comments (Atom)
would u plz tel me d details of these! its bit harder for me :p
ReplyDelete