Moon-Man.net Posted September 5, 2006 Share Posted September 5, 2006 Hey all,I have a script that will replace any files in a given directory with banned Charactures, However, how can i make this script be reocursive? EG. will also replace files in subdirectories of the given dir. I am totally stuffed for that:SThanks heaps EVERYONE for their help!Cheers,Nathan[code]#!/usr/bin/php<?PHP$dir = '/tmp/TESTING';$handle = opendir($dir);$cnt=0;echo "<------------Starting Replace!------------>\n" ;echo "\n";while(($file = readdir($handle)) !== false){// echo "File found: " .$file ."\n"; if (preg_match('/[' .preg_quote('\/ : * ? " < > |', '/') .']/', $file)){ echo "Bad file found: " .$file ." " ; $cnt++ ; $path = $dir . DIRECTORY_SEPARATOR . $file; if (!in_array($file, array('..', '.')) && is_file($path)){ $contents = file_get_contents($path); $newPath = $dir . DIRECTORY_SEPARATOR . preg_replace('/[' .preg_quote('\/ : * ? " < > |', '/') .']/', '', $file); echo "Replacing with " .$newPath ."\n" ;// if (file_put_contents($newPath, $contents) !== false){// unlink($path); //delete old file only if able to create new// } } }}echo "\n";echo "\n";echo "<------------Replace Finnished------------>\n" ;echo "There were " .$cnt ." Replacements Made\n" ;?>[/code] Quote Link to comment Share on other sites More sharing options...
btherl Posted September 5, 2006 Share Posted September 5, 2006 [code]function replace_bad_files($dir) { $handle = opendir($dir); ... while (($file = readdir($handle)) !== false) { # If we found a directory, call ourselves again! Simple $path = $dir . DIRECTORY_SEPARATOR . $file; if (is_dir($path)) { replace_bad_files($path); continue; # This will skip to the next file } ... }}[/code]The important steps here are[list][*]Make a function[*]Call the function recursively when you find a directory (as indicated by is_dir())[/list]To count the global number of replacements, you can either use a global variable, or you can have your function return the count, by adding "return $cnt;" at the end. In that case, the recursive call should be "$cnt += replace_bad_files($path)". Quote Link to comment Share on other sites More sharing options...
Moon-Man.net Posted September 5, 2006 Author Share Posted September 5, 2006 Awesome, so i can have a[code]if(is_dir($file)){ replace_bad_file($file) ;}[/code]Somewhere in there, and it will keep opening all unlimited ammounts of functions untill it is totally re-ocursive :DI diddnt know you call call the function you are in from within it :)Thanks Heaps.Cheers,Nathan Quote Link to comment Share on other sites More sharing options...
Jenk Posted September 5, 2006 Share Posted September 5, 2006 Use a static variable for counting, not global :) Quote Link to comment 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.