使用php搜索数据并从文本文件中删除数据 [英] Searching for data and removing data from a text file using php

查看:37
本文介绍了使用php搜索数据并从文本文件中删除数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序可以将数据列表导出到 .txt 文件中,但很多数据是不需要的.每条数据的格式如下:

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

将有 20 到 50 条这样的记录,我需要做的是搜索文件并删除具有以 0 开头的 CLASS 的记录.因此,如果它搜索并找到具有 CLASS 的广告记录以零开头,它将删除该记录中的所有内容.如果它是 .xml 会很容易,但它是一个 .txt 文件,所以它使事情变得困难.一旦它删除了所有坏数据,它将把好的数据保存在一个新文件中.

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.

推荐答案

$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');

这篇关于使用php搜索数据并从文本文件中删除数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆