...

View Full Version : File Parsing Function



thekevin07
03-06-2007, 09:02 AM
Hi

I need a way to parse a file based on the delimitation of either | tab or comma. Does anyone know the best way to do this that is the easiest? Also the file I am parsing might have a few empty strings between delimitation.

I know about preg_split so if this is the only way could someone provide a link that explains regular expressions because i dont get it.

Thanks

chump2877
03-06-2007, 10:26 AM
untested, but should give you the idea:


$file = file_get_contents($file_name);
$file_array = preg_split('/\||\t|,/',$file);
foreach ($file_array as $key => $val)
{
if (empty($val))
unset($file_array[$key])
}
$file_array2 = array_values($file_array);

Links:

http://us2.php.net/manual/en/function.preg-split.php
http://www.regular-expressions.info/
http://weblogtoolscollection.com/regex/regex.php

firepages
03-06-2007, 12:57 PM
unless you really need regex..


<?php
$lines=file($filename);
foreach($lines as $line){
$bits=explode('|', $line);
//do your stuff here
}
?>


if you expect pipes or commas in your files then explode may fail so look at something like fgetcsv (http://www.php.net/fgetscv) which has support for delimiters etc

thekevin07
03-06-2007, 09:46 PM
Thanks for the replies guys. What happens is i read each line in an array the first line contains fields that i need and i need to read these as the keys and then the delimited values in the second, third, fourth, etc line would be the values related to the keys now i think this association would be in a while loop or something but i cant seem to get my head around it. What i have come up with is below I also need that test to see if its empty I see that above so no need to put that in i can do it to save some time.


Thanks Again





$fcontents = file($target);

//get the fields
$fields = preg_split('/\||\t|,/',$fcontents[0]);

//count fields
$fCount=count($fields);
//main loop to deal with array of elements
$start=1;
while($start<=$fCount)
{

//split the fields up
$values=preg_split('/\||\t|,/',$fcontents[$start]);

///SOURCE TO MATCH FIELDS TO VALUES GOES HERE????
}

aedrin
03-06-2007, 10:22 PM
As firepages suggested, don't use preg when you don't need it. It's bulky and slow.



$lines = file($filename);
$list = array();
foreach ($lines as $line) {
$values = explode('|', $line);
if (sizeof($values) <= 1) continue; // 0 or only 1 element = empty, skip
$list[$values[0]] = array_splice($values, 1); // only get everything after the first element
}


I'm not sure if that is what you want though.

thekevin07
03-06-2007, 10:25 PM
Hi

actually i do need it i need to test for | commas and tabs either or and i may have more i just dont know what just yet im still in development. Can you tell me a little more on how your source code works and how it will work with my source code


thanks



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum