【问题标题】:Searching for data and removing data from a text file using php使用 php 搜索数据并从文本文件中删除数据
【发布时间】:2012-05-16 19:01:17
【问题描述】:

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

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 文件,这将很容易,所以它使事情变得困难。一旦它删除了所有坏数据,它将把好的数据保存在一个新文件中。

【问题讨论】:

    标签: php search text


    【解决方案1】:
    $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');
    

    【讨论】:

    • 有没有办法对此进行修改以删除结束日期超过当前日期的记录?
    • @jardane 您使用的是哪个 PHP 版本?
    • 不太确定,我只需要从“END DATE:”之后获取日期并将其与当前日期进行比较。
    【解决方案2】:
    $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');
    

    【讨论】:

    • 不引用确定错误的原因,我的程序只说错误而不是为什么。我知道数组最后需要一个 (),但 foreach 看起来很合适。
    • 你需要学会阅读错误日志。很明显,foreach 中缺少),这将导致它抱怨“___ 行出现意外的____”。如果有什么出乎意料的,那么你需要回头看看有什么遗漏。
    猜你喜欢
    • 2013-01-16
    • 2012-06-04
    • 2013-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-13
    • 1970-01-01
    • 2016-02-04
    相关资源
    最近更新 更多