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.

Link to comment
Share on other sites

<?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.

Link to comment
Share on other sites

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.

 

Link to comment
Share on other sites

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);

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.