Jump to content

[SOLVED] Delete entire line in text file if anything in the line matches search string


speaker219

Recommended Posts

Hello, how would I code a php script that would open a text file, look for a string i specified, and if it finds that string, it will delete the entire line in the text file that contained that text. I'm new to php, so sorry if this is really obvious.. :-\

Any help would be appreciated.

<?php
  if ($file=file("file.txt")) {
    foreach ($file as $txt) {
      if (stripos("search",$txt)!==false) {
        echo 'Found: '.$txt.'<br />';
      }
    }
  } else {
    echo 'Cannot read the file';
  }
?>

 

"string" is what you're wanting to look for - replace this with a variable containing the search text.

<?php
$content = file_get_contents("filename.txt");
$newcontent = str_replace("The string you want to find", "", "$content");
file_put_contents("filename.txt", "$newcontent");
?>

 

should do the trick.

I'm not sure you guys understand. I want it to delete the entire line after finding a specific string on that line. for example if the text file was:

Hello. this is line 1.
hello this is line 2
hello waka line 3
hello this is line 4

The key word is "waka" and I want the php script to delete the entire line of text that is on the same line as the word "waka" so it would look like this:

Hello. this is line 1.
hello this is line 2
hello this is line 4

thanks.

 

use this then.

<?php

$key = "waka";

//load file into $fc array

$fc=file("some.txt");

//open same file and use "w" to clear file

$f=fopen("some.txt","w");

//loop through array using foreach

foreach($fc as $line)
{
      if (!strstr($line,$key)) //look for $key in each line
            fputs($f,$line); //place $line back in file
}
fclose($f);

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.