Skip to content

Instantly share code, notes, and snippets.

@Ultrabenosaurus
Created September 24, 2012 13:22
Show Gist options
  • Save Ultrabenosaurus/3775923 to your computer and use it in GitHub Desktop.
Save Ultrabenosaurus/3775923 to your computer and use it in GitHub Desktop.
recursively change file extensions
/* 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);
@Ultrabenosaurus
Copy link
Author

Plan:

  • make recursive optional
  • only change extension if filename matches a regex pattern

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment