Search and Replace in Web Files

Home/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
";
$source = preg_replace($searchString,$newValue,$source);
file_put_contents($filename,$source);
$count++;
}
echo "Done - processed $count files";

echo "$dir
";
}

function walkDir($dir,$fx)
{
$arStack = array();
$fx($dir);
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";
}
}
closedir($dh);
}
if( count($arStack) )
{ foreach( $arStack as $subdir )
{ walkDir($subdir,$fx);
}
}
}

walkDir('./',callBackDir);

2011-03-02T23:14:27+00:00 June 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