首页 > 解决方案 > 仅在不匹配时保存一行

问题描述

我正在尝试从文件中保存数据,以防该行与字符不匹配。就我而言,我有一个数字列表,如果只有第一个字符不等于“0”-零-,我想保存这些数字

这是我的代码:

<?php
$cleanfile = "cleanfile.txt";
$handle = fopen("file.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        if ($line[0] != 0) {
            $save = file_put_contents($cleanfile, $line);
        }
    }

    fclose($handle);
} else {
    // error opening the file.
} 

我的 file.txt 有以下条目:

1
2
3457
94
31
54
039
3114
94
01
33333
1
2
3457
94
31
54
039
3114
94
01
33333
1
2
3457
94
31
54
039
3114
94
01
33333

标签: php

解决方案


您需要将FILE_APPEND标志传递给file_put_contents(),如下所示:

<?php
$cleanfile = "cleanfile.txt";
$handle = fopen("file.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        if ($line[0] != 0) {
            $save = file_put_contents($cleanfile, $line, FILE_APPEND);
        }
    }

    fclose($handle);
} else {
    // error opening the file.
}

但是,您的解决方案有点耗费资源,因为每次调用都会file_put_contents()产生不必要的开销。请将此演示视为更轻、更紧凑的解决方案:

<?php

// Collect all non-filtered lines.
$sieved = [];
// Read file.txt into an array, skipping empty lines.
foreach (file('file.txt', FILE_SKIP_EMPTY_LINES) as $line)
{
        if ($line[0] !== '0')
                $sieved[] = $line;
}

// Write out each array element, keeping the newlines from the input.
file_put_contents('cleanfile.txt', $sieved);

推荐阅读