Page 1 of 1
How to replace some text in a file after searching
Posted: Fri Oct 09, 2009 12:32 am
by waseem83
Can any body tell me how to replace some text after searching in file and if there is method it should not disturb the file text formate,mean every text line should be as it was before. Should not in one line text.
Thank you very much in advance
Re: How to replace some text in a file after searching
Posted: Fri Oct 09, 2009 12:53 am
by pa28
I think I know what you're looking for - let me know if I've misunderstood. As a simple example, suppose you want to replace all instances of the word "dog" with "cat":
Code: Select all
$filePath = "myfile.txt";
$contents = file_get_contents($filePath);
$contents = str_replace("dog", "cat", $contents);
file_put_contents($filePath, $contents);
First,
file_get_contents() opens the specified file, and reads the whole thing into a string, $contents.
str_replace() (the documentation is
here) will replace every occurrence of the first string - in this case "dog" - with the second - "cat".
str_ireplace() works exactly the same, but is case insensitive. You can then use
file_put_contents() to save the file.
Re: How to replace some text in a file after searching
Posted: Fri Oct 09, 2009 2:02 am
by jegan.aaodis
Thanks that was a good .
It helps me.