php - 用空白替换文本文件中的字符串,基本上删除它
问题描述
所以我能够找到并定位我在删除它时遇到问题的字符串(我的解决方案是用空白替换它)并用 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 " entry deleted-<br>";
}
else{
echo " entry not found<br>";
}
}
fclose($file);
}
解决方案
您的代码中有几个问题:
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";
}
推荐阅读
- javascript - Node.js:Socket.io 发出方法未触发
- java - JSoup 未完全呈现长页面
- javascript - 更改 div 时重新启动 javascript 变量
- c# - EF Core 3 未在第二级或更深层次加载相关数据
- django - 在 Django 应用程序中显示 PDF 并且需要选择一个被单击的单词并在警报框中显示相同的单词
- numbers - 不同的一列返回选定的列并使用 sybase 按日期 desc 排序
- visual-studio-2019 - Visual Studio 2019 - 设备按钮缺少 Hololens 模拟器
- reactjs - 从 React Bootstrap 表中禁用/删除分页号
- ios - 使用 [Navigation Controller, TabBarViewcontroller] 再次设置根控制器时发生内存泄漏 UIViewController
- c++ - 程序告诉我论点不匹配,即使它们明显匹配