PHP Read TXT, delete lines, create new file

0

I want to use PHP and xamp / wamp to do the following task on my computer without the need to upload / download:

I have dozens of TXT files on the computer, each TXT containing only 1 name per line, no dashes, periods,., etc.

I want to do a search, for example, for all people with surname "Silva" in those dozens of files, then PHP would read all the TXT files, move all the names with "Silva" to silva.txt and save the 2 files.

So far I have explained the following: The stop is to get the files and pass in the php by a foreach in each line, add in the database, but before add do a search if already exists the data in the new file, then save the 2 files.

Can anyone give me a light on how to do this?

I confess that I do not understand almost anything about PHP and I'm hitting my head to make this foreach in several files at the same time, create this BD, create a new file, move everything, see if it has repeated, save all files afterwards.

It's complicated to work ....

    
asked by anonymous 30.11.2016 / 20:10

1 answer

0
$base = __DIR__.DIRECTORY_SEPARATOR; // Diretório onde estão os arquivos txt.
$files = glob($base.'*.txt'); // Pega todos os arquivos que terminam com .txt

$search = 'silva'; // a palavra que deseja buscar
$found = array();
$arr = array();
// Itera os arquivos encontrados
foreach ($files as $file) {

    // Lê cada arquivo em um array
    $arr = file($file);
    foreach ($arr as $k => $v) {
        // Se encontrar a palavra, guarda no array $found e remove do array que leu o arquivo.
        if (stripos($v, $search) !== false) {
            $found[] = trim($arr[$k]);
            unset($arr[$k]);
        }
    }
    // Salva os dados no arquivo, com os nomes removidos
    if (!empty($found)) {
        file_put_contents($file, implode('', $arr));
    }

}
// salva todos os nomes encontrados
if (!empty($found)) {
    file_put_contents($base.'silva.txt', implode(PHP_EOL, $found));
}

unset($found, $arr);
    
30.11.2016 / 20:44