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.

Link to comment
Share on other sites

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 */
?>

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.