我想检测文本文件中是否存在单词,然后将其删除.. 所以,这是我的代码:
<?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.";
}
?>
我几个小时前就得到了这个工作。我对我的脚本进行了一些更改,不知何故,它不再起作用了。任何人都可以看穿代码并告诉我出了什么问题吗?
或者任何人都可以给出更简单的方式来做我想做的事?? 我的代码一团糟。.
我想检测文本文件中的单词是否存在,然后将其删除。
<?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";
}
?>