2 Replies - 1660 Views - Last Post: 26 January 2011 - 08:31 PM

#1 RodgerB   User is offline

  • D.I.C Lover
  • member icon

Reputation: 66
  • View blog
  • Posts: 2,284
  • Joined: 21-September 07

Delete a line in a text file if it equals a string

Posted 03 September 2008 - 10:47 PM

Description: 1) Copy and paste the function into a PHP script 2) Read the example on how to call the functionDeletes a line in a text file if it equals the $text_to_delete parameter of the function
// this function will delete a line in a file
// if it equals the $text_to_delete parameter
// created by Rodger Benham from 
function del_line_in_file($filename, $text_to_delete)
{
  // $file_contents = file_get_contents('blocked.squid');
  // split the string up into an array
  $file_array = array();
	
  $file = fopen($filename, 'rt');
  if($file)
  {
    while(!feof($file))
    {
      $val = fgets($file);
      if(is_string($val))
        array_push($file_array, $val);
    }	
    fclose($file);
  }
	
  // delete from file
  for($i = 0; $i < count($file_array); $i++)
  {
    if(strstr($file_array[$i], $text_to_delete))
    {
      if($file_array[$i] == $text_to_delete . "n") $file_array[$i] = '';
    }
  }
	
  // write it back to the file
  $file_write = fopen($filename, 'wt');	
  if($file_write)
  {
    fwrite($file_write, implode("", $file_array));
    fclose($file_write);
  }
}

// example usage
del_line_in_file("blocked.txt", "sex.com");



Is This A Good Question/Topic? 0
  • +

Replies To: Delete a line in a text file if it equals a string

#2 no2pencil   User is offline

  • Professor Snuggly Pants
  • member icon

Reputation: 6644
  • View blog
  • Posts: 30,937
  • Joined: 10-May 07

Re: Delete a line in a text file if it equals a string

Posted 03 September 2008 - 10:52 PM

This has been a popular requested technology lately. Thank you, as this will make a great addition to your contributions!
Was This Post Helpful? 0
  • +
  • -

#3 borninlyoko   User is offline

  • D.I.C Regular
  • member icon

Reputation: 7
  • View blog
  • Posts: 350
  • Joined: 03-December 09

Re: Delete a line in a text file if it equals a string

Posted 26 January 2011 - 08:31 PM

Thank you for this! I'll try and modify this to make it remove dead file links from the file directory on my upload page :D
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1