user2015533
user2015533

Reputation: 43

brackets regex php

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}

Upvotes: 0

Views: 96

Answers (1)

crackmigg
crackmigg

Reputation: 5881

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.

Upvotes: 1

Related Questions