John Roe
John Roe

Reputation: 186

Find and replace word in text file

I want to detect if a word in a text file exists, and then remove it.. so, this is my code:

<?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.";
}
?>

I got this work hours before.. I did some changes to my script and somehow, it didnt work anymore.. can anyone see through the code and tell me what is wrong??

or can anybody give simpler way to do what I want?? my code is messed..

Upvotes: 0

Views: 4251

Answers (1)

Hanky Panky
Hanky Panky

Reputation: 46900

I want to detect if a word in a text file exists, and then remove it..

<?php
 $search = $id;
 $filename="./user/".$_GET['own'].".txt";
 $contents = file_get_contents($filename);
 $contents = str_replace($id."\n", "", $contents);
 file_put_contents($filename,$contents);
?>

That is all that there is to it.

Edit:

To make this equivalent to your solution, one can use

<?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";
 }
?>

Upvotes: 3

Related Questions