我想检测文本文件中是否存在单词,然后将其删除..所以,这是我的代码:
<?php
$search = $id;
$lines = file("./user/".$_GET['own'].".txt");
// Store true when the text is found
$found = false;
foreach($lines as $line)
{
if(strpos($line, $search) !== false)
{
$found = true;
// open to read and modify
$file = "./user/".$_GET['own'].".txt";
$fh = fopen($file, 'r+');
$data = fread($fh, filesize($file));
$new_data = str_replace($id."\n", "", $data);
fclose($fh);
// Open to write
$fh = fopen($file, 'r+');
fwrite($fh, $new_data);
fclose($fh);
$status = "has been successfully deleted.";
}
}
// If the text was not found, show a message
if(!$found)
{
$status = "is not exist in your list.";
}
?>
我几小时前完成了这项工作..我对我的剧本进行了一些更改,不知何故,它不再工作了......任何人都可以通过代码看到并告诉我出了什么问题吗?
或者任何人都可以更简单的方式来做我想做的事情?我的代码乱了..
答案 0 :(得分:3)
我想检测文本文件中是否存在单词,然后将其删除..
<?php
$search = $id;
$filename="./user/".$_GET['own'].".txt";
$contents = file_get_contents($filename);
$contents = str_replace($id."\n", "", $contents);
file_put_contents($filename,$contents);
?>
这就是它的全部内容。
修改强>
要使其与您的解决方案等效,可以使用
<?php
$search = $id;
$filename="./user/".$_GET['own'].".txt";
$contents = file_get_contents($filename);
$contents = str_replace($id."\n", "", $contents,$count);
if($count>0)
{
file_put_contents($filename,$contents);
echo "found and removed";
}
else
{
echo "not found";
}
?>