0

可能重复:
从 CSV 文件中删除行

我有一个以这种方式构建的文件

numbers1;numbers;numbers;\n
numbers2;numbers;numbers;\n
numbers3 to delete;numbers;numbers;\n
numbers4;numbers;numbers;\n

如果我想删除包含“numbers3 to delete”的行(制作文件:

numbers1;numbers;numbers;\n
numbers2;numbers;numbers;\n
numbers4;numbers;numbers;\n

) 我怎样才能使用 fwrite?

我没有找到“删除行”功能,所以我在考虑计算字符直到 \n,但我仍然找不到“删除这么多字符”的方法。

有“del”字符吗?

4

2 回答 2

1

尝试这个-

$filename = "filename.txt";
$handle = @fopen($filename, "r");
if ($handle) {
    while (($buffer = fgets($handle, 1096)) !== false) {
        if(!stripos($buffer, "numbers3 to delete")
            $somecontent .= $buffer;
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}

if (is_writable($filename)) {

    if (!$handle = fopen($filename, 'W+')) {
         echo "Cannot open file ($filename)";
         exit;
    }

    if (fwrite($handle, $somecontent) === FALSE) {
        echo "Cannot write to file ($filename)";
        exit;
    }

    echo "Success, wrote ($somecontent) to file ($filename)";

    fclose($handle);

} else {
    echo "The file $filename is not writable";
}
于 2012-12-26T12:18:33.250 回答
0

感谢 Suresh,我最终得到了这个(在需要的地方添加了一个 !==,在 stripos 部分)

$eliminabile="numbers3 to delete;";

$handle = fopen("file.to.edit", "r");
if ($handle) {
    while (($buffer = fgets($handle)) !== false) {
        if(stripos($buffer, $eliminabile)!== 0)
        {
            $occorrenza .= $buffer;
        }
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}

if (is_writable("file.to.edit")) {

    if (!$handle = fopen("file.to.edit", "w+")) {
         echo "Cannot open file";
         exit;
    }

    if (fwrite($handle, $occorrenza) === FALSE) {
        echo "Cannot write to file";
        exit;
    }

    echo "Success, wrote ($occorrenza) to file)";

    fclose($handle);

} else {
    echo "The file is not writable";
}


?>
于 2012-12-26T14:46:48.217 回答