I need a free script to search and replace words on multiple files on same folder. Any script you can recommend?
Tia,
Andy
Moderator: General Moderators
Just to make sure about the replacing words part...dewaphp wrote:Guys,
I need a free script to search and replace words on multiple files on same folder. Any script you can recommend? 8)
Tia,
Andy
Code: Select all
<pre>
<?php
define ('N',"\n"); // prints better using <pre>, ignore this if you remove the echo's below.
$basedir = "files"; // declare the dir we are working with
if ($dir = @opendir($basedir)) { // open it up
while (($file = readdir($dir)) !== false) {
if ($file != "." and $file != ".." and substr($file,-4) == '.txt') { // verifiy, check for text-files
echo 'Old: '.$file.N; // displaying the old filename (debugging)
echo 'New: '.replacer($file).N.N; // displaying the new filename (debugging)
rename($basedir.'/'.$file, $basedir.'/'.replacer($file)); // actual renaming, using a function
}
}
closedir($dir); // close the directory
}
function replacer($word) {
$from[] = 'file'; // word 1
$to[] = 'JAM'; // word 1 replacement
$from[] = 'odd'; // word 2
$to[] = 'even'; // word 2 replacement
return str_replace($from, $to, $word); // replace the words using the arrays above
}
?>Code: Select all
Results:
Old: a file.txt
New: a JAM.txt
Old: another file.txt
New: another JAM.txt
Old: file number 3.txt
New: JAM number 3.txt
Old: foobar file.txt
New: foobar JAM.txt
Old: some other odd file.txt
New: some other even JAM.txt
Old: testing file.txt
New: testing JAM.txt
Old: the Z-file.txt
New: the Z-JAM.txt