Question

I know that we can delete a directory with the function:

rmdir($path);

However I wanted to delete a set of directories having the same prefix. For example there are the directories:

A_Folder1, A_Folder2, A_Folder3, B_Folder1, B_Folder2, B_Folder3

Then I wanted to delete all folders having prefix "A_" only.

Was it helpful?

Solution

It can be implemented for example as follow:

<?php

    $dir = '/path/to/some/dir/'; // notice: trailing slash!
    if ($handle = opendir($dir)) {
        while (false !== ($entry = readdir($handle))) {
            if (is_dir($dir . $entry) && strtolower(substr($entry, 0, 2)) == 'a_') {
                rmdir($dir . $entry);
            }
        }
        closedir($handle);
    }
?>

OTHER TIPS

There are at least 2 easy ways :

exec('rm -rf PREFIX*');

or you can use glob and is_dir functions

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top