Created
September 24, 2012 13:22
-
-
Save Ultrabenosaurus/3775923 to your computer and use it in GitHub Desktop.
recursively change file extensions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* taken from this comment on PHP.net - http://php.net/manual/en/function.rename.php#88081 */ | |
//changes files in $directory with extension $ext1 to have extension $ext2 | |
//note that if file.ext2 already exists it will simply be over-written | |
function changeext($directory, $ext1, $ext2, $verbose = false, $testing=true) { | |
if ($verbose && $testing) { echo "Testing only . . . <br />";} | |
$num = 0; | |
if($curdir = opendir($directory)) { | |
if ($verbose) echo "Opening $directory . . .<br />"; | |
while($file = readdir($curdir)) { | |
if($file != '.' && $file != '..') { | |
$srcfile = $directory . '/' . $file; | |
$string = "$file"; | |
$str = strlen($ext1); | |
$str++; | |
$newfile = substr($string, 0, -$str); | |
$newfile = $newfile.'.'.$ext2; | |
$dstfile = $directory . '/' . $newfile; | |
if (eregi("\.$ext1". '$' ,$file)) { # Look at only files with a pre-defined extension, '$' ensures the ext is only at they end of the filename | |
//I think the next two lines are unnecessary but they | |
//don't hurt anything so I'm leaving them | |
$fileHand = fopen($srcfile, 'r'); | |
fclose($fileHand); | |
if (!$testing) { | |
$result=rename($srcfile, $dstfile ); | |
if (!$result) echo "ERROR renaming $srcfile -> $dstfile<br />"; | |
} | |
if ($verbose) echo "$srcfile -> $dstfile<br />"; | |
} | |
if(is_dir($srcfile)) { | |
$num += changeext($srcfile, $ext1, $ext2, $verbose, $testing); | |
} | |
} | |
} | |
closedir($curdir); | |
} | |
return $num; | |
} | |
$testing=true; | |
$verbose=true; | |
//example usages, first run with $testing set to false, then change $testing to true to do them for real: | |
//changeext('your/directory', 'php', 'html', $verbose, $testing); | |
//changeext('your/directory', 'html', 'php', $verbose, $testing); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Plan: