在 PHP 中删除文本文件中的一行

3

我的想法是使用正则表达式在文本文件中找到某一行,然后将该行替换为空白,从而删除它。但是,我遇到了在文本文件中用空白覆盖该行的困难。

 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)){
                    echo preg_replace($line," ",$search);
                     echo "                          
                     entry deleted-<br>";
                   }
                   else{
                       echo "&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
                       entry not found<br>";
                   }
             }
             fclose($file);
         }

这不是字符类的工作方式。https://www.regular-expressions.info/charclass.html 另外,百分号(%)是您实际字符串中的内容还是您混淆了SQL通配符? - user3783243
这是实际字符串。 - jman
1个回答

6

这个问题可以更简单地分解成两个不同的问题。

  1. 在给定的字符串中找到子字符串的偏移量
  2. 使用剩余的字符串从偏移量末尾覆盖子字符串

你可以通过一个简单的 strpos() 搜索来完成第一个问题。这里不需要正则表达式。

第二种情况只需要知道字符串(文件)中子字符串的偏移量和长度,以便你可以取文件的剩余部分(文件的其余部分),从给定的偏移量处进行覆盖,并截断文件的其余部分。

有两种不同的方法来解决这个问题。

  1. 你可以在内存中执行整个操作
  2. 你可以在磁盘上执行它

如果文件很大(至少是文件大小的两倍),第一种方法显然需要更多的内存。第二种方法对内存更保守,但需要更多的工作才能实现。

内存中的实现

我将使用内存中的实现,因为它更易于编写和解释。

为了演示,让我们假设文件 database.txt 包含以下内容:

Line 1
Line 2
Line 3

假设我们想从这个文件中删除Line 2

$searchString = "Line 2\n"; // The line we want to remove

$string = file_get_contents("database.txt");
$offset = strpos($string, $searchString);

// The part of the file before the search string
$part1 = substr($string, 0, $offset);

// The part of the file after the search string
$part2 = substr($string, $offset + strlen($searchString));

// Now we glue them back together
file_put_contents("database.txt", $part1 . $part2);

你刚刚有效地删除了相关的那一行。现在这个文件应该是这样的...
第一行
第三行

如果我从表单的输入字段中获取文本,我的搜索字符串会是什么? - jman
搜索字符串是您要搜索的任何文本。与您在正则表达式中输入的相同的文本,但没有正则表达式。 - Sherif

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接