Search for content inside a file

Asked

Viewed 974 times

1

I would like to create a php file and make it scan a directory and search for files. txt

Scan for example all the . txt files from the /files/ folder (and all its Ubdirectories)

Each file he scans I need him to try to find inside the contents of the file, a keyword, like, "MARIA".

At the end he go through all the files, show something like this:

002023.txt - Maria found - Line 1 002023.txt - Maria found - Line 10 565454.txt - Maria found - Line 400 231332.txt - Maria found - Line 100

Someone can help me?

Thank you

1 answer

0

You can make a foreach using the glob() searching for all the .txt in a certain folder, and within this one foreach use the file_get_contents() for vascular each file .txt to find word occurrences.

Something more or less like this:

foreach (glob("SEU DIRETORIO/*.txt") as $arquivo) {
    $palavra = 'palavra procurada';
    header('Content-Type: text/plain');
    $conteudo = file_get_contents($arquivo);
    $parte = explode("\n", $conteudo);
    $base = preg_quote($palavra, '/');
    $base = "/^.*$base.*\$/m";
    if(preg_match_all($base, $parte[0], $achado)){
        echo "achou:\n";
        echo implode("\n", $achado[0]);
    }else{
        echo "não achou";
    }
}

I think that’s enough to help you.

  • Implementing Daniel’s answer: You can use a linux command (if you’re working on a linux server), searching for the files you want before working with them internally. Run tests with "exec": http://php.net/manual/en/function.exec.php and use the find linux command: https://www.vivaolinux.com.br/dica/Busca-por-string-dentro-dos-arquivos Good luck!

Browser other questions tagged

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