首页 > 解决方案 > 用空白替换文本文件中的字符串,基本上删除它

问题描述

所以我能够找到并定位我在删除它时遇到问题的字符串(我的解决方案是用空白替换它)并用 txt 文件中的新空白覆盖该行。

elseif ($inquiry=='delete'){
    $file= fopen("database.txt", "r+") or die("File was not found on server"); 
    $search = "/^[" . $Title . "%" . $Author . "%" . $ISBN . "%" . $Publisher . "%" . $Year . "]/i";

    //search function
    // What to look for

    // open and Read from file
    $lines = file('database.txt');//array

    foreach($lines as $line){
        // Check if the line contains the string we're looking for, and print if it does
        if(preg_match($search, $line)){
            file_put_contents($file, preg_replace($search,'',$line));
            echo "&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;entry deleted-<br>";
        }
        else{
            echo "&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;entry not found<br>";
        }
    }
    fclose($file);
}

标签: php

解决方案


您的代码中有几个问题:

1)您正在混合两种方法,fread()/fclose()files()/file_put_contents()自动打开和关闭文件。

2)file_put_contents需要一个文件名作为第一个参数,而不是您提供给他的文件处理程序。

3)您的正则表达式无效(根据您的需要):使用方括号[],您将匹配与作者、标题、...有至少一个共同字符的所有行

4)您需要将“元素已删除/未找到元素”消息放在循环之外。

这是使用file()and的解决方案file_put_contents():将文件作为数组读取,循环遍历该数组,直到找到要删除的元素,然后使用 将其删除unset。然后你可以重写整个文件。

$search = "/" . $Title . "%" . $Author . "%" . $ISBN . "%" . $Publisher . "%" . $Year . "/i";

// open and Read from file
$filename = 'database.txt' ;
$lines = file($filename);

$found = false ;
foreach($lines as $i => $line){
    // Check if the line contains the string we're looking for, and print if it does
    if(preg_match($search, $line)){
        unset($lines[$i]); // remove the line from the array
        $found = true ;
        break ; // if you are sure that you won't have duplicate lines, you can stop the loop after you find the element
    }
}

if($found)
{
    // rewrite the whole file
    file_put_contents($filename, implode('', $lines));
    echo "entry deleted";
}
else
{
    echo "entry not found";
}

推荐阅读