sasori Posted July 25, 2009 Share Posted July 25, 2009 hi i am having problem with writing and replacing strings to a file i have this 'testfile.txt' with the words adsfadsfasdfadsfasdfadfasddfsasori asdfadsfasdsasori asasdfasdfsasori adsfadfsasori now here's my php code $file = 'testfile.txt'; $fh = fopen($file,'r+'); $data = fread($fh,filesize($file)); $string = "sasori"; $replace = "replacement"; $change = str_replace($string,$replace,$data); fwrite($fh,$change); fclose($fh); whenever i run this on command prompt php.exe -f replace.php the data on the text file just appends the replacement..it doesn't replace the original search string adsfadsfasdfadsfasdfadfasddfsasori asdfadsfasdsasori asasdfasdfsasori adsfadfsasoriadsfadsfasdfadsfasdfadfasddfreplacement asdfadsfasdreplacement asasdfasdfreplacement adsfadfreplacement please tell me what to do in order to replace also those other strings Link to comment https://forums.phpfreaks.com/topic/167371-read-write-and-replace-help/ Share on other sites More sharing options...
Alex Posted July 25, 2009 Share Posted July 25, 2009 $fh = fopen($file,'w+'); Link to comment https://forums.phpfreaks.com/topic/167371-read-write-and-replace-help/#findComment-882537 Share on other sites More sharing options...
sasori Posted July 25, 2009 Author Share Posted July 25, 2009 $fh = fopen($file,'w+'); I tried what you said 'w+'..now all the words on the test file were gone..and none was written at all Link to comment https://forums.phpfreaks.com/topic/167371-read-write-and-replace-help/#findComment-882538 Share on other sites More sharing options...
sasori Posted July 25, 2009 Author Share Posted July 25, 2009 i was able to solve the problem my self ..thanks anyway $file = "testfile.txt"; $fh = fopen("testfile.txt",'r+'); if($fh){ $data = file_get_contents($file); rewind($fh); $change = str_replace("replaceme","withthis",$data); fwrite($fh,$change); } Link to comment https://forums.phpfreaks.com/topic/167371-read-write-and-replace-help/#findComment-882549 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.