Get all elements from a file until the next value

I have an flat file (a sample of which is below there are more and different records either side of this segment):

0 @F1@ FAM
1 MARR
2 DATE 18 OCT 1761
2 PLAC Crawley, Hampshire
1 HUSB @I1@
1 WIFE @I2@
1 CHIL @I3@
1 CHIL @I4@
1 CHIL @I5@
1 CHIL @I6@
1 CHIL @I7@
1 CHIL @I8@
1 CHIL @I9@
0 @F3@ FAM
1 MARR
2 DATE 5 JUN 1797
2 PLAC Crawley, Hampshire
1 HUSB @I8@
1 WIFE @I16@

I am using fgets to get each line of the file and then process it depending on the line contents. Or would reading each line into an array be a better bet?

What I need to do is to read each line between 0 @F??@ FAM and the next 0 @F??@ FAM into an array. There can be any number of rows between each instance.

Everything I have tried so far has failed.

Not asking for someone to write this for me but if you can give me some outline hints that would be gratefully received.

[php]<?php

$lines = explode("\r\n", ‘0 @F1@ FAM
1 MARR
2 DATE 18 OCT 1761
2 PLAC Crawley, Hampshire
1 HUSB @I1@
1 WIFE @I2@
1 CHIL @I3@
1 CHIL @I4@
1 CHIL @I5@
1 CHIL @I6@
1 CHIL @I7@
1 CHIL @I8@
1 CHIL @I9@
0 @F3@ FAM
1 MARR
2 DATE 5 JUN 1797
2 PLAC Crawley, Hampshire
1 HUSB @I8@
1 WIFE @I16@’);

$result = [];
$storeLines = false;

foreach ($lines as $line)
{
if (preg_match("/^0 @\F.+@ \FAM/", $line))
{
// flip the value of $storeLines
$storeLines = !$storeLines;
}
elseif ($storeLines)
{
$result[] = $line;
}
}

print_r($result);[/php]

[php]<?php

$lines = explode("\r\n", ‘0 @F1@ FAM
1 MARR
2 DATE 18 OCT 1761
2 PLAC Crawley, Hampshire
1 HUSB @I1@
1 WIFE @I2@
1 CHIL @I3@
1 CHIL @I4@
1 CHIL @I5@
1 CHIL @I6@
1 CHIL @I7@
1 CHIL @I8@
1 CHIL @I9@
0 @F3@ FAM
1 MARR
2 DATE 5 JUN 1797
2 PLAC Crawley, Hampshire
1 HUSB @I8@
1 WIFE @I16@
0 @F5@ FAM’);

$result = [];
$i = 0;
$storeLines = false;

foreach ($lines as $line)
{
if (preg_match("/^0 @\F.+@ \FAM/", $line))
{
$i++;
$storeLines = true;
}
elseif ($storeLines)
{
$result[$i][] = $line;
}
}

print_r($result);[/php]

Thanks Jim I will have a play with #2 as I also need the F?? in the array too.

Sponsor our Newsletter | Privacy Policy | Terms of Service