0

I am going to parse a log file and I wonder how I can convert such a string:

[5189192e][game]: kill killer='0:Tee' victim='1:nameless tee' weapon=5 special=0

into some kind of array:

$log['5189192e']['game']['killer'] = '0:Tee';
$log['5189192e']['game']['victim'] = '1:nameless tee';
$log['5189192e']['game']['weapon'] = '5';
$log['5189192e']['game']['special'] = '0';
Robert
  • 19,800
  • 5
  • 55
  • 85
  • You could use `$arr = explode(' ', $str);` to split `$str` by space. Then you could do the same on `=` to get your key->value pairs. – Danny Beckett May 08 '13 at 12:32
  • sscanf() might be an option - http://www.php.net/manual/en/function.sscanf.php if the log file entries always follow this basic structure – Mark Baker May 08 '13 at 12:37

3 Answers3

1

The best way is to use function preg_match_all() and regular expressions.

For example to get 5189192e you need to use expression

/[0-9]{7}e/

This says that the first 7 characters are digits last character is e you can change it to fits any letter

/[0-9]{7}[a-z]+/ 

it is almost the same but fits every letter in the end

more advanced example with subpatterns and whole details

<?php
    $matches = array();
    preg_match_all('\[[0-9]{7}e\]\[game]: kill killer=\'([0-9]+):([a-zA-z]+)\' victim=\'([0-9]+):([a-zA-Z ]+)\' weapon=([0-9]+) special=([0-9])+\', $str, $matches);
    print_r($matches);
?>
  • $str is string to be parsed
  • $matches contains the whole data you needed to be pared like killer id, weapon, name etc.
Robert
  • 19,800
  • 5
  • 55
  • 85
  • Parse error: syntax error, unexpected '(' on line 2 However, I am totally satisfied with sebataz answer. Thanks anyway :) – Jan Cieslik May 08 '13 at 14:45
  • because there is one '' that need to be escaped :) regex was okay :) I've checked it with online regex :) – Robert May 08 '13 at 19:29
0

You definitely need a regex. Here is the pertaining PHP function and here is a regex syntax reference.

Stefano Sanfilippo
  • 32,265
  • 7
  • 79
  • 80
0

Using the function preg_match_all() and a regex you will be able to generate an array, which you then just have to organize into your multi-dimensional array:

here's the code:

$log_string = "[5189192e][game]: kill killer='0:Tee' victim='1:nameless tee' weapon=5 special=0";
preg_match_all("/^\[([0-9a-z]*)\]\[([a-z]*)\]: kill (.*)='(.*)' (.*)='(.*)' (.*)=([0-9]*) (.*)=([0-9]*)$/", $log_string, $result);

$log[$result[1][0]][$result[2][0]][$result[3][0]] = $result[4][0];
$log[$result[1][0]][$result[2][0]][$result[5][0]] = $result[6][0];
$log[$result[1][0]][$result[2][0]][$result[7][0]] = $result[8][0];
$log[$result[1][0]][$result[2][0]][$result[9][0]] = $result[10][0];
// $log is your formatted array
sebataz
  • 1,025
  • 2
  • 11
  • 35