How to replace some text in a file after searching

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
waseem83
Forum Commoner
Posts: 54
Joined: Tue Jun 23, 2009 3:51 am
Contact:

How to replace some text in a file after searching

Post 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
pa28
Forum Newbie
Posts: 7
Joined: Mon Oct 05, 2009 9:26 pm

Re: How to replace some text in a file after searching

Post 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.
jegan.aaodis
Forum Newbie
Posts: 15
Joined: Fri Oct 09, 2009 1:56 am

Re: How to replace some text in a file after searching

Post by jegan.aaodis »

Thanks that was a good .
It helps me.
Post Reply