How to Search and Replace using PHP

Post Reply
Tony
Lieutenant
Lieutenant
Posts: 86
Joined: Tue Jul 21, 2009 4:11 pm

How to Search and Replace using PHP

Post by Tony » Sun Nov 29, 2009 4:39 am

For when you need to find that variable or string in all your files. Or when you need to change the name of a variable in all your scripts. These Search and Replace scripts operate on all the files of a given type an any directory.

The way the scripts are written you cannot use the # character in the search string (but you can modify the scripts if needed). If you need to use " in the search string or new value string you will need to use \" in the string in the script.

This is the Search Script.

Code: Select all

<?php
// this script will search all the files of a specific type in a specific directory and list those that contain a specific string
//
// enter the string you want to find - it cannot contain the # char or the script will fail
$searchString = "find this";
// enter tha path to the search directory, and the file type to search
$path = "path_to_files/*.htm";
//
// do not change anything below this line
$searchString = "#".$searchString."#";
$globarray = glob($path);
if ($globarray) foreach ($globarray as $filename) {
  $source = file_get_contents($filename);
  if (preg_match($searchString,$source)) echo "$filename <br>";
  $count++;
}
echo "Done - processed $count files";
?>
This is the Replace Script.

Code: Select all

<?php
// this script will search all the files of a specific type in a specific directory and do a mass change
//
// enter the string you want to change - it cannot contain the # char or the script will fail
$searchString = "find this";
// enter the new value for the string
$newValue = "change to this";
// enter the path to the search directory, and the file type to search
$path = "path_to_files/*.htm";
//
// do not change anything below this line
$searchString = "#".$searchString."#";
$globarray = glob($path);
if ($globarray) foreach ($globarray as $filename) {
  $source = file_get_contents($filename);
  $source = preg_replace($searchString,$newValue,$source);
  file_put_contents($filename,$source);
  $count++;
}
echo "Done - processed $count files";
?>
As always, take a backup before making any changes.
Post Reply

Return to “PHP & MySQL”