/**
* Deletes from $dir all files, names of which not matching regexp
* @param $dir directory path (without tailing slash)
* @param $regexp regular expression to check filenames with preg_match.
* Non mathing files will be deleted.
* @param int $silent if 0, all messages (info / error) will be echoed, if 1 -
* only error messages, if 2 - all output will be suppressed (defaults to 1)
* @return int number of files, matching pattern and thus not deleted, -1 on failure
*/
function cleanDir($dir, $regexp, $silent=1)
{
if(($dh=opendir($dir))!==false)
{
$noError = true;
$filesStillInDir = 0;
if(!$silent)
echo "Cleaning dir $dir";
while ($file = readdir($dh))
{
if($file != ".." && $file!=".")
{
if(is_dir($dir."/".$file)) // If directory - recursive call
{
$filesStillInSubDir = cleanDir($dir."/".$file,$regexp,$silent);
if(-1 != $filesStillInSubDir)
{
$filesStillInDir+=$filesStillInSubDir; // increase count of files, still remaining in current directory
if(0 == $filesStillInSubDir) // no files, matching pattern, found in dir - delete it
{
if(!$silent)
echo "Dir $dir/$file empty - deleting";
if(!@rmdir($dir."/".$file))
{
$noError = false;
if($silent < 2)
echo "Error deleting dir after cleaning: $dir/$file
";
}
}
}
else
{
if($silent < 2)
echo "Error cleaning dir $dir/$file
";
$noError = false;
}
}
else // is file => check name and, if not matches - delete it
{
if(preg_match($regexp, $file) == 0)
{
if(!@unlink($dir."/".$file))
{
$noError = false;
if($silent < 2)
echo "Error deleting file $dir/$file
";
}
}
else
$filesStillInDir++;
}
}
}
closedir($dh);
if($noError)
return $filesStillInDir;
else
return -1;
}
if($silent < 2)
echo "Error opening dir $dir for cleaning!
";
return -1;
}
Дирактории, в которых не осталось файлов, также удаляются (кроме родительской директории, для которой функция была вызвана изначально).
Пример вызова (удаление всех файлов, кроме файлов интернационализации в Java):
$propFilesFound = cleanDir($pathToUnpack,'/Resources.*\.properties$/');