Thursday, February 5, 2009

Some useful PHP function (RegEx):

  1. Email address validation:

    function isEmail($email){
    $regex = "/\w+@\w+.\w+/";
    return preg_match($regex, $email);
    }


  2. URL validation:

    function isURL($url){
    $regex = "/(https?ftpfile):\/\/.\w+.\w\w+/";
    return preg_match($regex, $url);
    }


  3. Validate IP:

    function isIp($ip){
    $block = "(25[012345]2[01234]\d[01]?\d\d?)";
    $regex = "/^($block\.$block\.$block\.$block)$/";
    return preg_match($regex, $ip);
    }


  4. 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);
    }


  5. 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;
    }


  6. 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.";
    }


1 comment:

  1. would u plz tel me d details of these! its bit harder for me :p

    ReplyDelete