基于字符串匹配在PHP中解析脱节的TXT文件?

时间:2016-02-28 07:42:52

标签: php parsing preg-match

所以我有一个脱节的TXT文件。如何解析它以便它可以使用字符串匹配来计算数据?

从下面的示例我想:

timestamp = 
src=
dst=
user=
agent=
request:
url=

如果在行上找不到该值,则该值应为NULL。我尝试使用preg_match(),但它不执行整个文件。没有产出。

谢谢。

Sample.txt的

  

2016-02-24 13:54:23 Local0.Info 172.16.120.4 1 1456311263.806656820   ASD_MX600流量src = 108.177.15.189 dst = 213.130.115.218 protocol = udp   sport = 443 dport = 61907 pattern:1 all

     

2016-02-24 13:54:23 Local0.Info 172.16.120.4 1 1456311263.500015263   ASD_MX600 urls src = 172.16.41.15:62490 dst = 144.76.76.148:80   MAC = 00:1B:0D:63:84:00   用户= CN =史密斯\约翰,OU = S-HS,OU = SACC,DC = ABC,DC =组织,DC = AB   agent ='Mozilla / 5.0(Windows NT 6.1; WOW64; rv:36.0)Gecko / 20100101   seb / 2.0 SEBKEY'的请求:GET   http://something.com/theme/image.php/clean/page/1455532301/icon

     

2016-02-24 14:29:14 Local0.Info 172.16.120.4 1 1456313354.489880924   ASD_MX600 urls src = 172.16.41.143:57256 dst = 74.125.232.155:443   mac = 00:1C:B0:10:A8:00请求:UNKNOWN   https://4780928.fls.doubleclick.net/ ...

另外,我在这里问了一个类似的问题 - > Complex parsing a text file in PHP - 但是没有空间要求对其进行额外的扩展,因此发布了一个新问题。谢谢。

SK

PS:我尝试过的代码但是没有用。

示例1

$myfile = fopen("C:\Documents and Settings\Administrator\Desktop\LogCatcher Script\SyslogCatchAll-2016-02-25.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file


while(!feof($myfile)) {

   $line = fgets($myfile) . "<br>";// you can do the explode and assignment here.
    //example
    $row_data = explode("   ", $line);     //FIRST BLAST

   $timestamp = $row_data[0] ;         //Pick up the timestamp for Column 1
   $timestamp;

   //SECOND BLAST
   $remainingData = explode(" ",$row_data[3]);     //chop it off
   $src =   $remainingData[4];
   $src = ltrim($src, "src=");

    $dst=   $remainingData[5];
    $dst = ltrim($dst, "dst=");

    $usr = $remainingData[7];
    if (preg_match('/user=/',$usr))
      {
    $usr = ltrim($usr, "user=");
      }
      else  {
      $usr = "No User Found";
      }   

...这是它开始痉挛的地方,因为不是每一行都有“user =”......

示例2 我尝试使用其他用户代码的另一种方式。

<?php
$rows = explode("\n", file_get_contents('sample.txt'));
$result = array();

foreach ($rows as $row) {
    if (trim($row) == "") {
        continue;
    }
    $timeMatches = array();
    $reTime = "/([0-9-]* [0-9:]*) /";
    preg_match($reTime, $row, $timeMatches);
    $re = "/src=(.*) dst=(.*) mac=(.*) user=(.*) agent=(.*) request: (.*) (.*)/";
    $matches = array();
    preg_match($re, $row, $matches);
    $result[] = array('time' => $timeMatches[1], 'src' => $matches[1]
                , 'dst' => $matches[2], 'mac' => $matches[3]
                , 'user' => $matches[4], 'agent' => $matches[5]
                , 'method' => $matches[6], 'url' => $matches[7]);
}

var_dump($result);

?>

运行并且不显示任何内容。刚结束。

0 个答案:

没有答案