所以我的想法是使用正则表达式在文本文件中查找特定行,然后用空白替换该行,实质上将其删除。但是,我正在努力在文本文件中重写带有空白的行
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 "
entry not found<br>";
}
}
fclose($file);
}
这个问题可以更简单地分解为两个不同的问题。
- 查找给定字符串中子字符串的偏移量
- 用字符串的其余部分覆盖从其偏移量末尾开始的子字符串
您可以通过简单的操作完成第一个strpos()
针/大海捞针搜索。这里不需要正则表达式。
第二种情况只需要知道字符串(文件)中子字符串的偏移量和长度,这样您就可以获取字符串的其余部分(文件的其余部分)并从给定的偏移量开始覆盖,截断字符串的其余部分文件。
此解决方案有两种不同的方法。
- 您可以在内存中完成整个操作
- 你可以在磁盘上完成
如果文件很大(至少是文件大小的两倍),第一个显然需要更多内存。第二种方法在内存上更加保守,但需要更多的工作来实现。
内存中实现
我将使用内存中的实现,因为它更容易编写和解释。
为了演示的目的,我们假设该文件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);
您实际上已经删除了有问题的行。该文件现在应该如下所示...
Line 1
Line 3
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)