What's wrong with these Regular Expressions?

Discussion in 'PHP' started by Darden12, Jan 4, 2009.

  1. #1
    I'm a newbie to Regular Expressions, and I'm wondering why the following regular expression line does not yield the required results.

    preg_match_all("/[\d]{1}[\d]{1}\d?[.][\d]{1}[\d]{1}\d?[.][\d]{1}[\d]{1}\d?[.][\d]{1}[\d]{1}\d?\s\-/", $Article, $matches);

    I'm trying to isolate the IP addresses in my access log files for my domain. The above regular expression will provide me a list something like the following. As you see, the IP's are obviously incorrect, at least until you get to the first period in the address:

    070.108.214.195 -
    170.108.214.195 -
    270.108.214.195 -
    370.108.214.195 -
    4216.154.18.235 -
    570.108.214.195 -
    670.108.214.195 -
    7216.154.18.235 -
    865.55.105.19 -
    965.55.105.19 -
    10216.154.18.235 -
    11202.156.14.79 -

    Again, my question is how to tweak (or if necessary, completely rework) the above regex code so that the IP address will be found correctly.

    Thanks,

    PS My ultimate hope is to isolate the information provided for each IP and to save it to a stats database.
     
    Darden12, Jan 4, 2009 IP
  2. Danltn

    Danltn Well-Known Member

    Messages:
    679
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    120
    #2
    "/^((0|1)?\d{1,2}|2([0-4]\d|5[0-5]))(\.((1|0)?\d{1,2}|2([0-4]\d|5[0-5]))){3}$/"
    Example

    $ips = <<< ips
    070.108.214.195 
    170.108.214.195 
    270.108.214.195 
    370.108.214.195 
    4216.154.18.235 
    570.108.214.195 
    670.108.214.195 
    7216.154.18.235 
    865.55.105.19 
    965.55.105.19 
    10216.154.18.235 
    11202.156.14.79 
    ips;
    
    foreach ( explode("\n", str_replace("\r", '', $ips)) as $line )
        if ( preg_match("/^((0|1)?\d{1,2}|2([0-4]\d|5[0-5]))(\.((1|0)?\d{1,2}|2([0-4]\d|5[0-5]))){3}$/", trim($line)) )
            echo 'Success - ' . $line . "\n";
        else
            echo 'Fail - ' . $line . "\n";
    PHP:
    Returns:
    Success - 070.108.214.195 
    Success - 170.108.214.195 
    Fail - 270.108.214.195 
    Fail - 370.108.214.195 
    Fail - 4216.154.18.235 
    Fail - 570.108.214.195 
    Fail - 670.108.214.195 
    Fail - 7216.154.18.235 
    Fail - 865.55.105.19 
    Fail - 965.55.105.19 
    Fail - 10216.154.18.235 
    Fail - 11202.156.14.79 
    Code (markup):
    Only matches exact Ips.
     
    Danltn, Jan 4, 2009 IP