Search and Replace in Web Files

/Search and Replace in Web Files

This handy function will search and replace all instances of a search term in every file with the PHP extension, across all directories and subdirectories. Upload the file to your root directory and run it.

function callbackDir($dir){ 

$searchString = "searchforthis";
$newValue = "replacewiththis";

// directory, and file type
$path = "$dir/*.php";

$searchString = "#".$searchString."#";
$globarray = glob($path);
if ($globarray) foreach ($globarray as $filename) {
  $source = file_get_contents($filename);
  if (preg_match($searchString,$source)) echo "$filename <br>";
  $source = preg_replace($searchString,$newValue,$source);
echo "Done - processed $count files";

  echo "$dir<br />";

function walkDir($dir,$fx)
  $arStack = array();
  if( ($dh=opendir($dir)) )
  { while( ($file=readdir($dh))!==false )
    { if( $file=='.' || $file=='..' ) continue;
      if( is_dir("$dir/$file") )
      { if( !in_array("$dir/$file",$arStack) ) $arStack[]="$dir/$file";
  if( count($arStack) )
  { foreach( $arStack as $subdir )
    { walkDir($subdir,$fx);


2011-03-02T23:14:27+00:00June 9th, 2010|PHP Snippets|0 Comments

About the Author:

Warren Chandler is a freelance web programmer and web developer, based in Frinton on Sea, Essex. Warren specialises in web programming, web design, corporate identity, copy writing, SEO, logo and print media for home, work, and mobile platforms.

Leave A Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.