Question

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';
Was it helpful?

Solution 2

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

OTHER TIPS

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top