madolia Posted September 18, 2006 Share Posted September 18, 2006 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 Quote Link to comment https://forums.phpfreaks.com/topic/21114-script-to-automatically-replace-variable-name-in-all-files-in-a-directory/ Share on other sites More sharing options...
Daniel0 Posted September 18, 2006 Share Posted September 18, 2006 I haven't tested it, but it should work: [code]<?phpfunction 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");?>[/code][b]Edit:[/b] Note that it works recursively. If you wan't to remove that feature, just comment out [code]replace_var($directory.$item);[/code] (inside the function). Quote Link to comment https://forums.phpfreaks.com/topic/21114-script-to-automatically-replace-variable-name-in-all-files-in-a-directory/#findComment-93820 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.