We help IT Professionals succeed at work.

Using php delete line from txt file.

justmelat
justmelat asked
on
22,435 Views
Last Modified: 2008-02-01
I am doing some forward thinking on a project i'm working on.

With the help of some gurus here I got the attached code working perfectly.  I am anticipating that my boss will want to be able to delete a word from this text file at some point.

I came across this set of instructions while trying to figure out if it is possible.
Use filegetcontents() to read the file into a string.

Use explode() to get the contents of the file/string into an array (since they're just single items, right?).

Loop through the array to remove what you wanted to remove.

Output the array (using implode()) back to the file.

My questions:

1) is it possible to delete a line from a text file using php?
2) are the instructions above doable?
3) if they are doable how would i code it and incorporate it into the code attached?

I am thinking that I will have button that takes the user to another page where a dropdown box containing the results (contents of
txt file, which is just one column of names) is located, then they just select the words they want removed from the text file.

I know u are saying, it should be in a db, but for some unknown reason, they want this file to remain a txt file.
<?php
 
session_start();
$phpself = $_SERVER['PHP_SELF'];
 
if ($_POST['btnAddWord'] == 'Add' )
	{
		$newWord = trim($txt_newWord);
		//echo "Word to be added: ".$newWord."<br><br>";
 
		$myFile = 'filterlist.txt';
		//echo $myFile."<br><br>";
		
		file_put_contents($myFile, $newWord . PHP_EOL, FILE_APPEND) or die("can't open file");
		
		/*$fh = fopen($myFile, 'a') or die("can't open file");
		
		$stringData = $newWord;
		fwrite($fh, $stringData);*/
		
		//fclose($fh);
		echo "<b><font size=4 color=#000080>New Word Successfully added to Bad Word Filter List.</b></font>";
		echo "<script>setTimeout(\"document.location.href = 'badWordFilter.php'\",2000)</script>";
 
	}
	else 
{
		
	echo "<b><font size=5 color=#000080>Bad Word Filter</font></b><br>";
 
	echo "<form method=POST action=$phpself name=frmWordFilter>";
	
	
	echo "<br><b>Add New Word to Filtered List:</b><br><input type=text name=txt_newWord size=35>";
	echo "<p><input type=submit value=Add name=btnAddWord></p>";
	echo "</form>";
echo "<hr color=#000080 width=85% size=3>";
$myFile = "filterlist.txt";
$fh = fopen($myFile, 'r');
$theData = implode(', ', file($myFile));
 
 
$lines = file('filterlist.txt');
echo "<br><b>Current List:  </b><br><br>";
// Loop through our array, show HTML source as HTML source; and line numbers too.
 
foreach ($lines as $line_num => $line) 
{
	echo "Word #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}
 
// Another example, let's get a web page into a string.  See also file_get_contents().
$html = implode('', file('filterlist.txt'));
 
//$theData = implode(",", fread($fh, filesize($myFile)));
fclose($fh);
 
echo "<br><b>Current List:  </b>".$theData;		
}
 
?>

Open in new window

Comment
Watch Question

This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
when you use file() be sure to handle the newline character at the end of each line.

try something like this if you run into problems with the newline chars

$theData = implode(', ', array_map('trim',file($myFile)));
I have written two functions for you below, since I'm not sure I understand what you want to do.

The first function, delete_line_by_number() will remove line X out of any file. If you had a file "myfile.txt" with 300 lines in it, and you wanted to delete the 290th one, you would use:

delete_line_by_number(290, "myfile.txt");

The second function, delete_line(), will remove any line matching string X out of any file. If you had a line that said "here is one line" in the file "myfile.txt", you would use:

delete_line("here is an entire line to remove", "myfile.txt");

If you need further clarification, I am glad to help.
function delete_line_by_number($line, $file)
{
	$contents = array();
	$new_contents = "";
	$number_of_lines = 0;
 
	if(file_exists($file))
	{
		if(is_writable($file))
		{
			// open the file as an array, each line as an element
			if($contents = file($file))
			{
				$number_of_lines = count($contents);
				if($line <= $number_of_lines)
				{
					// remove extra whitespace from each line
					$contents = array_map("trim", $contents);
					
					// remove the line in question
					unset($contents[($line-1)]);
					
					// put the lines back together with a \n between each
					$new_contents = implode("\n", $contents);
					
					// open the file and delete its old contents
					if($handle = fopen($file, 'w'))
					{
						if(fwrite($handle, $new_contents) !== false)
						{
							// it worked
							return true;
						}
					}
					else
					{
						trigger_error("$file could not be opened for writing", E_USER_NOTICE);
						return false;
					}
				}
				else
				{
					trigger_error("$file only has $number_of_lines lines, so line $line could not be removed", E_USER_NOTICE);
					return false;
				}
			}
			else
			{
				trigger_error("$file is not readable", E_USER_NOTICE);
				return false;
			}
		}
		else
		{
			trigger_error("$file is not writable", E_USER_NOTICE);
			return false;
		}
	}
	else
	{
		trigger_error("$file does not exist", E_USER_NOTICE);
		return false;
	}
	
}
 
function delete_line($find, $file)
{
	$contents = array();
	$new_contents = "";
	$find = trim($find);
	$return = false;
 
	if(file_exists($file))
	{
		if(is_writable($file))
		{
			// open the file as an array, each line as an element
			if($contents = file($file))
			{
					// remove extra whitespace from each line
					$contents = array_map("trim", $contents);
					
					// loop through each line and see if it's the one we want<br />
					foreach($contents as $line_number => $line)
					{
						$lowercase_line = strtolower($line);
						$lowercase_find = strtolower($find);
						if($lowercase_line == $lowercase_find)
						{
							// this is where we remove the line
							unset($contents[$line_number]);
							$return = true;
						}
					}
					
					// put the lines back together with a \n between each
					$new_contents = implode("\n", $contents);
					
					// open the file and delete its old contents
					if(!$handle = fopen($file, 'w'))
					{
						trigger_error("$file could not be opened for writing", E_USER_NOTICE);
						return false;
					}
					else
					{
 
						if(fwrite($handle, $new_contents) !== false)
						{
							// it worked
							return $return;
						}
					}
			}
			else
			{
				trigger_error("$file is not readable", E_USER_NOTICE);
				return false;
			}
		}
		else
		{
			trigger_error("$file is not writable", E_USER_NOTICE);
			return false;
		}
	}
	else
	{
		trigger_error("$file does not exist", E_USER_NOTICE);
		return false;
	}
	
}
 
if(delete_line_by_number(3, "test.txt"))
	echo "A line was removed";
else
	echo "A line could not be removed";
	
if(delete_line("some text", "test.txt"))
	echo "A line was removed";
else
	echo "A line could not be removed";

Open in new window

Commented:
For bad word filtering, you should simply use preg_replace
$bad_words = array ( '/hello/' , '/world/' );
$replace = array();
$string = "This string no more contains bad words like hello and world";
echo preg_replace( $bad_words, $replace, $string);

Open in new window

NerdsOfTechTechnology Scientist
CERTIFIED EXPERT

Commented:
Maybe give some extra time for a solution? ... Oh well.
function delete_line_by_number($line, $file)
{
 $myFile = file('filterlist.txt');
 $data = '';
 
 for ($i=0; $i<count($myFile); $i++)
 {
 
  if (!$i == $linenum)
  {
         echo "LINE #<b>$i</b> : " . htmlspecialchars($myFile[$i]) . "<br />\n"; // output HTML
  } else 
  {
 
   // Remove Line
   unset($myFile[$i]);
 
   // Re-index:
   $myFile = array_values($myFile);
 
   echo "REMOVED LINE #<b>$i</b> : " . htmlspecialchars($myFile[$i]) . "<br />\n"; // output HTML
 
  }
 
 }
 
  //Then delete the original file
 
 if (file_exists('myfile.txt'))
 {
  unlink('myfile.txt');
 }
 
 //and write the new data
 
 $fp = fopen('myfile.txt',"w");
 
 if ($fp)
 {
  fwrite($fp,$data);
  fclose($fp);
 }
}
 
 
 
 
 
 
function delete_line($find, $file)
{
 $myFile = file('filterlist.txt');
 $data = '';
 
 for ($i=0; $i<count($myFile); $i++)
 {
  if (!strstr($myfile[$i],$find))
  {
   $data .= $file[$i]."\n";
  } else 
  {
    // Remove Line
    unset($myFile[$i]);
 
    // Re-index:
    $myFile = array_values($myFile);
 
    echo "REMOVED LINE #<b>$i</b> : " . htmlspecialchars($myFile[$i]) . "<br />\n"; // output HTML
  }
 }
 
  //Then delete the original file
 
 if (file_exists('myfile.txt'))
 {
  unlink('myfile.txt');
 }
 
 //and write the new data
 
 $fp = fopen('myfile.txt',"w");
 
 if ($fp)
 {
  fwrite($fp,$data);
  fclose($fp);
 }
}

Open in new window

Hi NerdsOfTech,

You won't require to unlink the file. If you have write permission "w" mode crates a blank file for you to write even if the file exists and have data. also using "wt" will be better idea on text files for OS like windows

so
$fp = fopen('myfile.txt',"wt");
will be enough

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.