0

Searched through this site and tried some suggestions but no luck so far.

I have a bunch of files containing this string in the filename: " 2" for example: test 2.php or imagename 2.jpg

I want to remove all files that contain the " 2" string from root folder (/httpsdocs) and all subfolders.

Tried this:

foreach (glob("* 2.*") as $filename) {
    unlink($filename);

and this works but obviously only in root folder.

How can I get this to work recursively?

Marc Le Bihan
  • 2,308
  • 2
  • 23
  • 41
  • Does this answer your question? [List all the files and folders in a Directory with PHP recursive function](https://stackoverflow.com/questions/24783862/list-all-the-files-and-folders-in-a-directory-with-php-recursive-function) – Nico Haase Feb 05 '21 at 15:20

2 Answers2

0

Have you tried something like that ?

public function removeFilesOnDirectory($path)
{

    $files = glob($path . '/*');
    foreach ($files as $file) {
        if(is_dir($file)) {
            $this->removeDirectory($file);
        } else {
            if (str_contains($file, '2' /* Your constraint */)) {
                unlink($file);
            }
        }
    }

    return;
}

Call this->removeDirectory(/* your path */);

Works for me, just testing it :)

Regards

0

I would use a built-in RecursiveDirectoryIterator to make it as simple as possible.

<?php

$directoryIterator = new RecursiveDirectoryIterator("/httpsdocs");

foreach(new RecursiveIteratorIterator($directoryIterator) as $file) {
    if(strpos($file->getFilename(), ' 2.')) {
        // if filename has specified substring, remove the file
        unlink($file);
    }
}

If you use PHP8 you can take advantage of the new str_containt() function instead of strpos().

Karol Dabrowski
  • 1,190
  • 1
  • 8
  • 18