Print

Printed September 9, 2010 from B&T's Tips & Scripts
http://tips-scripts.com


Search and Replace

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.

You can download this script as a .txt file.  Remember to rename the file as a .php file.

- - Start Script Here - -
<?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";
?>

- - End Script Here - -

This is the Replace Script.

You can download this script as a .txt file.  Remember to rename the file as a .php file.

- - Start Script Here - -
<?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";
?>

- - End Script Here - -

As always, take a backup before making any changes.