Jump to content


Photo

script to automatically replace variable name in all files in a directory


  • Please log in to reply
1 reply to this topic

#1 madolia

madolia
  • New Members
  • Pip
  • Newbie
  • 3 posts

Posted 18 September 2006 - 02:54 AM

hi all.

i have a directory with about 25 php files. instead of manually changing one by one, is there anyone who knows how to generate a script which could open each file, search for the variable name and replace it with the new one and save the script.

kindly advice.

thanx

#2 Daniel0

Daniel0
  • Staff Alumni
  • Advanced Member
  • 11,956 posts

Posted 18 September 2006 - 06:11 AM

I haven't tested it, but it should work:
<?php
function replace_var($directory='.',$old_var_name='',$new_var_name='')
{
	if(substr($directory,-1) != '/')
	{
		$directory .= "/";
	}
	
	if($dh = @opendir($directory))
	{
		while($item = @readdir($dh) != false)
		{
			if($item != '.' && $item != '..')
			{
				if(is_dir($directory.$item))
				{
					replace_var($directory.$item);
				}
				else {
					$file_contents = @file_get_contents($directory.$item);
					$file_contents = str_replace('$'.$old_var_name,'$'.$new_var_name,$file_contents);
					
					$fp = fopen($directory.$item,'w');
					fwrite($fp,$file_contents);
					fclose($fp);
				}
			}
		}
	}
	@closedir($dh);
}

replace_var("/var/www/some_script","old_var","new_var");
?>

Edit: Note that it works recursively. If you wan't to remove that feature, just comment out
replace_var($directory.$item);
(inside the function).




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users