jardane
jardane

Reputation: 471

Searching for data and removing data from a text file using php

I have a program that exports a list of data in to a .txt file, a lot of the data is unneeded. Every piece of data is formatted like this:

PUB DATE: 03/16/2012
END DATE: 06/10/2012
PUB:  my company
ADNUM: 00237978
CLASS: 0825
AD TYPE: RE
COLUMNS: 2.00
GRAPHIC FILE: some_image.jpg
AD TEXT: Text
*** end of ad

There will be between 20 and 50 records like this, what i need to do is search the file for and delete records that have a CLASS that starts with a 0. So if it searches and finds an ad record with a CLASS that begins with zero it will delete everything that is in that record. This would be easy if it was .xml but it's a .txt file so it makes things hard. once it has deleted all the bad data it will then save the good data in a new file.

Upvotes: 0

Views: 311

Answers (2)

message
message

Reputation: 4603

$keep = array();
$filePath = '/path/to/txt/file.txt';
$textData = file_get_contents($filePath);
$records = explode('*** end of ad', $textData);
foreach ($records as $record) {
    if (empty($record)) {
        continue;
    }

    if ( ! preg_match('/CLASS:\s+?0/', $record)) {
        $endDate = array();
        preg_match('/END\sDATE:\s?\d{0,2}\/\d{0,2}\/\d{0,4}/', $record, $endDate);
        if ( ! empty($endDate)) {
            $parts = explode(':', $endDate[0]);
            $dateString = trim($parts[1]);
            $date = DateTime::createFromFormat('d/m/Y', $dateString);
            $currentDate = new Date();
            $currentDate->setTime(0, 0, 0);
            if ($currentDate->format('U') > $date->format('U')) {
                continue;
            }
        }
        $keep[] = $record;
    }
}
file_put_contents($filePath, implode('*** end of ad', $keep) . '*** end of ad');

Upvotes: 1

miki
miki

Reputation: 695

$keep = array;
foreach(explode('*** end of ad', file_get_contents($filePath) as $record):
  if(!preg_match('^CLASS:\s*0825'/, $record))
    $keep[] = $record;
endforeach;

file_put_contents($filePath, implode('*** end of ad', $keep) . '*** end of ad');

Upvotes: 0

Related Questions