Jump to content

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


madolia

Recommended Posts

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
I haven't tested it, but it should work: [code]<?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");
?>[/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).

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.