Use Regexiterator in directories to find folder or file

Asked

Viewed 37 times

0

I’m not very good with regex and need a help to do a sort of search between files from part of the folder or file name that is at the end

$find = 'oo';
$directory = 'd:\\test';
    $search = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($directory, FilesystemIterator::SKIP_DOTS),
            RecursiveIteratorIterator::SELF_FIRST
        );


    $search = new RegexIterator($search, '/'.$find.'/i');

Folders and files in the directory:

d:\test\bar foo;
d:\test\foo bar;
d:\test\text.txt;
d:\test\foo.txt;

The goal is to find folders or file parts with oo

d:\test\foo bar;
d:\test\bar foo;
d:\test\foo.txt;

2 answers

1

Some time ago I needed to do a search similar to yours, I used the code below to solve the problem:

<?php

function listarArquivos($diretorio, $nomeArquivo) {
    $encontrados = "";
    $ponteiro = opendir($diretorio);

    while ($nome_itens = readdir($ponteiro)) {
        $itens[] = $nome_itens;
    }

    sort($itens);

    foreach ($itens as $listar) {
        if ($listar != "." && $listar != "..") {
            if (is_dir($diretorio . '/' . $listar)) {
                $encontrados .= listarArquivos($diretorio . '/' . $listar, $nomeArquivo);
            } else {
                if (preg_match('/' . $nomeArquivo . '/i', $listar)) {
                    $encontrados .= $diretorio . '/' . $listar . " <br> ";
                }
            }
        }
    }

    return $encontrados;
}

try {

    echo listarArquivos('C:\www\layout', "(nome)*(ou)*(partes)");

} catch (Exception $e) {
    echo $e->getMessage();
}

I hope it helps!

  • I tested and it worked, but I want to make use of Recursiveiteratoriterator by being faster, even if by thousandths

0

You can use the following code:

<?php 

$find = 'min';
$directory = new RecursiveDirectoryIterator('C:\www\layout');
$flattened = new RecursiveIteratorIterator($directory);

$files = new RegexIterator($flattened, '/'.$find.'/i');

foreach($files as $file) {
    echo $file . PHP_EOL . '<br>';
}

I removed it from here: https://stackoverflow.com/questions/3321547/how-to-use-regexiterator-in-php

  • has a problem, when searching the folder, in the loop ends up showing all its files that have no part of the search string

  • In fact, it will read all the directories in your base folder and will take the entire file path and check if there is what you are searching for. Example: "C: www layout MIN.txt" and "C: www layout Minimo algumacoisa.txt".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.