1

In my directory i have these files:

JBBsongs.html, JBB.php, ArrangeJBB.html, Follow.html and follow.php

I know I can delete a specific file using unlink

<?php

unlink('test.html');
?>

But how can I delete specific files that contains "JBB" on their names?

Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39

3 Answers3

3

You can loop through your directory using scandirand check for files containing JBB using strpos and then unlink it.

    $dir="./";
    $files=scandir($dir);
    if(is_array($files)){
        foreach($files as $file){
            if(is_file($dir.$file) && strpos($file,"JBB")!==false){
                unlink($dir.$file);
            }
        }
    }
Atal Prateek
  • 541
  • 3
  • 7
2

Use strstr () function.

Assuming you already have your file names in an array, you can do something like

<?php
$files = Array ('JBBsongs.html', 'JBB.php', 'ArrangeJBB.html', 'Follow.html', 'follow.php');

foreach ($files as $file)
{
    if (strstr ($file, "JBB"))
    {
        unlink('test.html');
    }
}
?>

strstr returns false if the needle (the searched string) is not present in the first string. In this way only the desired files will be unlinked.

Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
1

you can loop among all the files in a folder using readdir or scandir. once you have the filename you can check strpos of JBB. if the strpos value is equal to or greater than 0. then you can call the unlink function on the filename. This will delete the file