Regular expression, preg_match (), and storage in an array

1

Hello . I have a .txt ( pastebin ) that contains the log of the connected clients on a server openvpn and the format of each of the lines is as below:

CLIENT_LIST orion-01889596000195    177.43.212.110:28763    172.16.191.145  872199  860412  Wed May 25 07:22:52 2016    1464171772  UNDEF

I'm using the preg_match() function to store each result at a position in an array. I made the code two ways.

First Form

$log = "log.txt";
$handle = fopen($log, "r");

$inclients = false;
$cdata = array();

while (!feof($handle))
{
 $line = fgets($handle, 4096);

 if (substr($line, 0, 11) == "CLIENT_LIST")
 {
  $inclients = true;
 }
 if ($inclients)
 {
  preg_match("/\w+-\d{14}/", $line, $cdata);
  preg_match("/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\:[0-9]+/", $line, $cdata[1]);
  preg_match("/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/", $line, $cdata[2]);
  preg_match("/\s+[0-9]+/", $line, $cdata[3]);
 return var_dump($cdata[0], $cdata[1], $cdata[2], $cdata[3]);
 }
}

Second way

if ($inclients)
{
 preg_match("/\w+-\d{14}\s+[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\:[0-9]+\s[0-9]+\. [0-9]+\.[0-9]+\.[0-9]+\s+[0-9]+\s+[0-9]+/", $line, $cdata);
 var_dump($cdata);
}

Problems I encountered in the first form: the name ( orion-01889596000195 ) and the 1st ip ( 177.43.212.110:28763 ) I was able to store in $cdata[0] and% but when storing the 2nd ip ( 172.16.191.145 ) in $cdata[1] it returns to get the 1st ip but without the numbering after ":" . And the other data I need to store are: 872199 , 860412 and 1464171772 I could not get into them.

Problems that I encountered in the second form: I believe the following information was stored in $cdata[3] : $cdata[0] and therefore I do not know how to get each information separately. Although I managed to capture the 860412 result I was unable to move between Wed May 25 07:22:52 2016 until you reached 1464171772 . p>

Thank you for helping me!

    
asked by anonymous 30.05.2016 / 06:05

1 answer

0

Viewing your pastebin I see that the fields are separated by tabs , and as you mentioned UNDEF is in the background a null, undefined value that can be converted to empty string. So you can do it like this:

function processador($str){
    $partes = preg_split("/\t/", trim($str));
    $data = array_slice($partes, 1); 
    return array_map("filtro", $data);
}
function filtro($str){
    return str_replace("UNDEF", "", $str);
}

$linhas = array_filter(explode("\n", $string));
$resultado = array_map("processador", $linhas);

echo var_dump($resultado);

ideone: link

    
30.05.2016 / 07:47