cjd143SD
cjd143SD

Reputation: 869

what is the best way to split string data that is delimited in php

Looking for php help, best practice. What is a good way to break these lines? I was looking into explode or is a regex better? and then maybe display them into a table? thanks for your input.

input file:

PRE:abc:KEY1:null:KEY2:/myproject/data/dat_abc_2010120810.gz1
PRE:def:KEY1:sdsu:KEY2:mail_abc.dat.2010120810.gz1

expected output or web page for display:

PRE  KEY1 KEY2
===  ==== ======================================
abc  null /myproject/data/dat_abc_2010120810.gz1
def  sdsu mail_abc.dat.2010120810.gz1

Upvotes: 3

Views: 393

Answers (2)

netcoder
netcoder

Reputation: 67695

explode will work just fine:

$fp = fopen('myfile.txt', 'r');
while ($line = fgets($fp))
   $parts = explode(':', $line);
   $array = array();
   for ($i=0; $i<count($parts); $i+=2) {
      $array[$parts[$i]] = isset($parts[$i+1]) ? $parts[$i+1] : 'null';
   }
   print_r($array);
}

Will output:

Array
(
    [PRE] => abc
    [KEY1] => null
    [KEY2] => /myproject/data/dat_abc_2010120810.gz1
)
Array
(
    [PRE] => def
    [KEY1] => sdsu
    [KEY2] => mail_abc.dat.2010120810.gz1
)

Upvotes: 4

mishmash
mishmash

Reputation: 4458

If you have a file like that I would do it in two steps if I were you...

1st step

Use file() to get an array representing the file.

2nd step

Now you can use explode() to get all the different columns and output them.

Quick example:

<?php
$output = "";

$file = file("data.txt");
foreach ($file as $line)
{
    $cols = explode (":", $line);
    $output .= "{$cols[0]} {$cols[1]}";
}
?>

Hope this helps.

Upvotes: 5

Related Questions