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
Link to comment
Share on other sites

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).
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.