How to parse fixed width column text in php?

First of all, there was sscanf:

$vars = sscanf($string, '%s %s %d %s');

It is optimized for whitespace separated values, and you can specify the variable type already (%s = string; %d = integer)(; even name the variables but that is not demonstrated in the example).

Example/Demo:

$lines = explode("\r\n", $input);

foreach($lines as &$line)
{
    $line = sscanf($line, '%s %s %d %s');
}

var_dump($lines);

Output:

array(6) {
  [0]=>
  array(4) {
    [0]=>
    string(8) "DB2INST1"
    [1]=>
    string(14) "db2jcc_applica"
    [2]=>
    int(11446)
    [3]=>
    string(29) "10.0.0.209.51406.120606004531"
  }
  [1]=>
  array(4) {
    [0]=>
    string(8) "DB2INST1"
    [1]=>
    string(14) "db2jcc_applica"
    [2]=>
    int(11448)
    [3]=>
    string(29) "10.0.0.209.51407.120606004536"
  }
  [2]=>
  array(4) {
    [0]=>
    string(8) "DB2INST1"
    [1]=>
    string(14) "db2jcc_applica"
    [2]=>
    int(13762)
    [3]=>
    string(29) "10.0.0.206.57473.120606024909"
  }
  [3]=>
  array(4) {
    [0]=>
    string(5) "ADMIN"
    [1]=>
    string(14) "db2jcc_applica"
    [2]=>
    int(15220)
    [3]=>
    string(29) "10.0.0.210.52248.120606045402"
  }
  [4]=>
  array(4) {
    [0]=>
    string(8) "DB2INST1"
    [1]=>
    string(8) "php-fpm:"
    [2]=>
    NULL
    [3]=>
    NULL
  }
  [5]=>
  &array(4) {
    [0]=>
    string(8) "DB2INST1"
    [1]=>
    string(14) "db2jcc_applica"
    [2]=>
    int(16547)
    [3]=>
    string(29) "10.0.0.202.52042.120606065813"
  }
}

Leave a Comment