0

How to delete all strings in a txt file which contains some words?

I try to do it using this script:

$f = "somefile.txt";
$str=file_get_contents($f);
$oldMessage=$_POST['label'];
$deletedFormat=' ';
$str=str_replace("$oldMessage", "$deletedFormat",$str);
file_put_contents($f, $str);

But my script deletes only one word not the whole string. Ideas?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Darkwind
  • 345
  • 9
  • 20
  • 1
    The answer is already here: http://stackoverflow.com/questions/2352153/search-for-phrase-word-in-text-files-with-php – Lars Hansen Sep 15 '15 at 08:17
  • 3
    What do you mean by `string`? A single word is a string, a whole line is a string, the whole file is a string. – Phil Cross Sep 15 '15 at 08:18
  • What are you trying to achieve? Do you want to just delete the entire `$oldMessage` if there is a certain word or? It would help if we could see the contents of `$oldMessage` probably. – SidOfc Sep 15 '15 at 08:34
  • I want to delete the line contains variable - $oldMessage – Darkwind Sep 15 '15 at 11:19

1 Answers1

1

This is my solution:

$f = "somefile.txt";
$file = fopen ($f, 'r');
$oldMessage=$_POST['label'];
$deletedFormat=' ';
while(!feof($file)){
    $line = fgets($file);
    if (strpos($line , $oldMessage)) $arr[] = $line;
}
$str=file_get_contents($f);
foreach($arr as $needle){
    $str=str_replace($needle, $deletedFormat,$str);
}
file_put_contents($f, $str);
Dmitrii Cheremisin
  • 1,498
  • 10
  • 11