Jump to content

replace/deletes a specific line in a text file


spaceman12

Recommended Posts

The title says it all,..well as all u can see, there are many methods to accomplish this done but not before undergoing through a heavy tasking process. For instance,

1. Open the file

2. Reads the content of the file into array.

3. Find out the desire line of text that we want to replace.

4. Make that line of text as variable and assigns with the new data(that we want to replace) as its values.

5.open another file.

6.Write the whole contents to the file opened in 5.

7. Put the contents back to the file of original.

 

Can anyone contributes a better way to get this done? Like replace/delete a specific line without affecting other characters or anything therein?

Thanx.

 

P.S

reading and using str_replace to make the alteration always ends up in giving some kind of result beyond desired after the first round of code execution.

Method 1: put the lines into a database then use LIKE to find the lines that contain your value to be replaced.

 

Method 2 (using your original scenario):

<?PHP
$file = "somefile.csv"; /* original file */
$file2 = "somefile2.csv"; /* secondary file you mentioned */
$haystack = file($file); /* put contents into an array */
$needle1 = "what I am looking for"; /* value to be replaced */
$needle2 ="My replacement text"; /* value doing the replacing */
for($i=0;$i<count($haystack);$i++) { 
$haystack[$i'] = str_ireplace($needle1, $needle2, $haystack[$i]); /* case insensitive replacement */
}
$content = implode("\n", $haystack); /* put array into one variable with newline as delimiter */
file_put_contents($file, $content); /* over write original with changes made */
file_put_contents($file2, $content); /* write to secondary file */
?>

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.