spaceman12 Posted March 10, 2011 Share Posted March 10, 2011 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. Quote Link to comment https://forums.phpfreaks.com/topic/230189-replacedeletes-a-specific-line-in-a-text-file/ Share on other sites More sharing options...
litebearer Posted March 10, 2011 Share Posted March 10, 2011 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 */ ?> Quote Link to comment https://forums.phpfreaks.com/topic/230189-replacedeletes-a-specific-line-in-a-text-file/#findComment-1185527 Share on other sites More sharing options...
AbraCadaver Posted March 10, 2011 Share Posted March 10, 2011 file_put_contents('file.txt', str_replace($search, $replace, file_get_contents('file.txt'))); Quote Link to comment https://forums.phpfreaks.com/topic/230189-replacedeletes-a-specific-line-in-a-text-file/#findComment-1185698 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.