Search code examples
phpregexstringtext-parsing

Parse string containing square-braced path keys and key=value expressions and make a multidimensional array


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';

Solution

  • 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