search and replace in a folder full of text files


New member
I am making a website using php to create html files. I have made quite a lot my site . But I am trying to search and replace text in a folder which contains text files. I have tried str_replace and it didn't work. Then I have tried explode and implode but that does not seem to work. Can anyone help? It should be very simple but I just cannot find the code.
Last edited by a moderator:
Here's a simple illustration of how to accomplish this:


// text files path
$folder = 'path/to/your/folder/';

// Enter search and replace strings
$search = 'old_text';
$replace = 'new_text';

// Open the folder

if ($handle = opendir($folder)) {
// Loop through each file in the folder
while (false !== ($file = readdir($handle))) {
// Make sure it's a text file
if ('.' !== $file && '..' !== $file && is_file($folder . $file) && pathinfo($file, PATHINFO_EXTENSION) == 'txt') {
// Read the contents
$contents = file_get_contents($folder . $file);

// search and replace content
$updatedContents = str_replace($search, $replace, $contents);

// Write the updated contents back to the file
file_put_contents($folder . $file, $updatedContents);

echo "Updated file: $file <br>";

i hope it will work for you.