How to list files in PHP with a specific name?

2

Good Morning I have the code below.

 <?php
 $diretorio = "../../arquivos/nest"; 
 $ponteiro  = opendir($diretorio);
 while ($nome_itens = readdir($ponteiro)) {
$itens[] = $nome_itens;
}
sort($itens);
foreach ($itens as $listar) {
if ($listar!="." && $listar!=".."){ 
            if (is_dir($listar)) { 
                    $pastas[]=$listar; 
            } else{ 
                    $arquivos[]=$listar;
            }
   }
}
if ($pastas != "" ) { 
foreach($pastas as $listar){
print "<img src='pasta.png'> <a href='$diretorio/$listar'download>$listar</a><br>";} 
   }
if ($arquivos != "") {
foreach($arquivos as $listar){
print "<a href='$diretorio/$listar' download>$listar</a><br>";}
}
?>

The Code works correctly, my doubt is. I want to create a variable that will have a specific text and that will serve as a filter to show the files it has in the directory with the variable in question.

Example: In the variable contain the information "Cars", when generating the listing only the files in the directories that have in the name of the "Cars" files appear.

    
asked by anonymous 09.03.2017 / 12:54

1 answer

6

I think you've done it in a more complicated way.

It was simpler to use the glob function containing the desired expression:

 $expr = '/caminho/para/pasta/Carros*.txt';

 foreach (glob($expr) as $path) {
       echo $path;
 }

Another way is to use the strpos function to see if you have the desired part in the file name.

In the case, I'll use a more current way to list directories, which is through FileSystemIterator

$arquivos = array();
$termo = 'Carros';
$iterator = new FileSystemIterator('diretório/desejado/aqui');
foreach ($iterator as $file) {

      $filename = $file->getRealpath();

      if (strpos($filename, $termo) !== false) {
         $arquivos[] = $filename;
      }
}
    
09.03.2017 / 12:56