I'm using a simple glob routine to list files in a folder/directory and would like to exclude a few files whose file names contain certain keywords.

For instance below, I'm excluding any files that contain the term "thumb" (which are thumbnails). I would like to exclude several others from the results... but I cannot get an array of excluded terms to work. How can I use this SAME routine to exclude other terms from the results?


$files = glob("/home/*.*");
for ($i=0; $i<count($files); $i++)
{
$num = $files[$i];

if (!stristr($num,'thumb'))
{
echo "$num<br>";
}
}

    $files = glob("/home/*.*"); 
    $exclude = array('thumb','other','ignore','etc');
    for ($i=0; $i<count($files); $i++) 
    { 
       $num = $files[$i]; 
       $err = 0;
       foreach($exclude as $term)
       {
          if (stristr($num,$term)) 
          { 
             $err++;
          } 
       }
       if( !$err > 0 )
       {
          echo "$num<br>";
       }
       $err = 0;
    } 

    HTH

    nvm failed

      You could do this with less loops using a regular expression, e.g.:

      $files = glob("*.*");
      $exclude = array('thumb','other','ignore','.php');
      
      $regexp = implode('|', array_map('preg_quote', $exclude));
      
      foreach($files as $file)
      {
      	if(preg_match("/$regexp/i", $file))
      		continue;
      
      // handle $file here
      echo "found file: $file\n";
      }

        Thanks so much for trying, but that didn't work. I tried something similar earlier... couldn't get the array to work with glob. Looks like the reg exp below will do the trick.

          Yep, the reg exp worked great!!! Thanks so much for your help. I guess this is must be the only way to configure such exceptions with glob.

            I don't understand, if it worked your original way for one exception, why wouldn't it work the way I did it for any exception?

            ./boggle oh well... glad you got it working =D

              I don't understand it either. It looks like it should work but I couldn't get it going with PHP 5.3. In fact I tried several other similar array routines with Glob... could get none of them to function. (I thought I was losing my mind!) The reg exp is the only method that has worked thus far with Glob. I sincerely appreciate your help!!

                You could do the same thing without using the regexp too... here's one way:

                $files = glob("*.*"); 
                $exclude = array('thumb','other','ignore','etc'); 
                foreach($files as $file)
                {  
                foreach($exclude as $term) { if (stripos($file,$term) !== false) { continue 2; // break out of 2 levels of loops } } echo "$file<br>"; }

                  Hey Derokorian, I tried your script again... and IT DID work!!! I'm so sorry... I must have done something stupid when I tested it, not hard for me to do. Anyway, it does work... you were right after all!!!

                    Write a Reply...