0

Using regex in php how would I store each IP into a separate variable?

It will grab content from a log file that will look like this.

1/27/2013 7:34:14 AM Removed        {109.104.19.75}
1/27/2013 7:34:16 AM Added          {98.119.183.235}
1/27/2013 7:34:17 AM Removed        {98.119.183.235}
1/27/2013 7:34:34 AM Added          {89.155.107.178}
1/27/2013 7:34:35 AM Removed        {89.155.107.178}
5
  • Do they have to be in separate variables, why not just store them all in an array? Commented Jan 27, 2013 at 13:43
  • Just iterate over the lines inside the logfile (read it line by line) and extract the ip with a simple regex. You can built an array of ips using the iteration counter as key. Why make things more complicated? Commented Jan 27, 2013 at 13:45
  • preg_match_all("/.*{(.*)}.*/", $a, $b);var_dump($b[1]); Commented Jan 27, 2013 at 13:46
  • 2
    You don't even need regex here. Just simple substring would do. Commented Jan 27, 2013 at 13:57
  • Thanks farmer1992, that's exactly what I needed! Commented Jan 29, 2013 at 3:22

1 Answer 1

1

This script reads your logfile and returns the IP-addresses as an array. I would recommend to use an array for this, because you can handle it better with PHP than separate variables:

function readIps($filename, $unique = false) {
    $lines  = file($filename);
    $result = array();

    foreach ($lines as $line) {
        if (preg_match('/\{([^\}]+)\}$/', $line, $matches)) {
            $result[] = $matches[1];
        }
    }

    return $unique ? array_values(array_unique($result)) : $result;
}

This script assumes, that you are sure, that only IP addresses are listed between the brackets at the end of each line. If this is not the case, the regex would also match other things than IP addresses and would have to be more special.

Call it with only your file name and you get a list with every occurance of an IP list, as often as it occurs. Call it with the second parameter set to true and you get a list with every IP only occurring once.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.