Select a file by name in PHP

3

Good afternoon, I need help selecting a file for its name in PHP. I use the naming pattern starting with the file creation date in the format: 20160111_ALGUMA_COISA and I need my PHP to select only the file by the part until the DATA, ignoring the rest _ALGUMA_COISA.

Can anyone help with this part of the code?

Thanks, I'm waiting

    
asked by anonymous 11.01.2016 / 18:23

7 answers

2

Using substr () function

$str = '20160111_ALGUMA_COISA.txt';
echo substr($str, 0, 8); // retorna '20160111'

The value zero is the starting point of the string. The value 8 is the end point where the string will be "cut". Therefore, it will return the first 8 characters.

Why value 8? By logical deduction, the part you want to extract will always have 8 characters. Of course it will not be possible when we get to a year with more than 5 houses. The year 9999 is the limit year. But you can be sure that no one will care about your code on January 1, 10000.

    
11.01.2016 / 18:33
2
<?php

$str = '20160111_ALGUMA_COISA';

echo substr($str, 0, strpos($str,"_ALGUMA_COISA"));

?>

Result:

  

20160111

EDIT:

Assuming the file name is formatted as follows: DATA_ALGUMA_COISA and I want to remove the "_ALGUMA_COISA", I need to use a function that "searches" inside my string with the filename, cutting from the beginning (position 0 ) to the index found "_ALGUMA_COISA".

  

strpos - Find the position of the first occurrence of a string

     

substr - Returns a part of a string

In short lines, I "shorten" the string what I want, as far as what I does begins to appear.

20160111 _ALGUMA_COISA

The advantage of using this approach is that you can have any date formatting (with N characters), you will always delete _ALGUMA_COISA

.

    
11.01.2016 / 18:33
2

You say the default is "20160111_ALGUMA_COISA"

It means that it would (date) (some) (thing).

You can use this to get each die:

<?php

$nome = '20160111_ALGUMA_COISA'; //nome
$param = explode('_', $nome); //irá dividir cada "_"
$data = $param['0']; // resultará em 20160111.
 //$alguma = $param['1']; 
 //$coisa = $param['2'];

?>

Note: this will only work if there is _ between each parameter.

If you want to make this a "human" date do this:

<?php

$data = $param['0']; // 20160111 - ver exemplo anterior ou diretamente do $nome;
$ano = substr($data, 0, 4); // 2016 - corta até o 4 digito
$mes = substr($data, 4, 6); // 01 - do 4º ao 6º digito
$dia = substr($data, 6, 8); // 11 - do 6º ao 8º digito

$dataHumana = $dia.'/'.$mes.'/'.$ano; // 11/01/2016

?>
    
11.01.2016 / 18:46
2

I do not understand if you want to get the files, or if they are already listed and you want to extract the number forward.

If you want to extract the number you can use explode so (this way the explode will only divide by the first underline):

<?php
$filename = '20160111_ALGUMA_COISA.txt';
list($id, $name) = explode('_', $filename, 2);

echo 'Id: ', $id, PHP_EOL;
echo 'Nome: ', $name, PHP_EOL;

You can also use strtok :

<?php
$filename = '20160111_ALGUMA_COISA.txt';
$id = strtok($filename, '_');
$name = strtok('');

echo 'Id: ', $id, PHP_EOL;
echo 'Nome: ', $name, PHP_EOL;

If you want to remove the extension you can use rtrim , like this:

<?php
$filename = '20160111_ALGUMA_COISA.txt';
list($id, $name) = explode('_', $filename, 2);

$name = rtrim($name, '.txt');

echo 'Id: ', $id, PHP_EOL;
echo 'Nome: ', $name, PHP_EOL;

Or:

<?php
$filename = '20160111_ALGUMA_COISA.txt';
$id = strtok($filename, '_');
$name = strtok('');

$name = rtrim($name, '.txt');

echo 'Id: ', $id, PHP_EOL;
echo 'Nome: ', $name, PHP_EOL;

Now if what you want is to list the files that begin with numbers you can try to use glob :

<?php
foreach (glob('[0-9]*[_]*.txt') as $filename) {
    echo $filename, '<br>';
}

Documentation:

11.01.2016 / 18:49
1

With strstr it is also possible. link

   <?php
   $filename = '20160111_ALGUMA_COISA.txt';

   //omitindo o terceiro parâmetro - default false-(retornaria _ALGUMA_COISA.txt)
   $newFile  = strstr($filename, '_');
   echo $newFile; 
    
13.01.2016 / 12:26
0

Eduardo You can also do it this way

 $arquivo = "20160111_ALGUMA_COISA";
 $arquivo  = explode("_", $arquivo);
 $arq1 = trim($arquivo[0]); // 1º
 $arq2 = trim($arquivo[1]); // 2º

 echo $arq1.'<br>';
 echo $arq2;  
    
12.01.2016 / 00:32
-1

Very interesting people the various collaborations, but follow the final code for those who need (thanks):

$data = date('Ymd'); //pega data no formato
$str = $data;//cria variavel com a data

$filename = substr($str, 0, 8);//ajusta para identificar a parte inicial do arquivo
echo "<br>Localizar arquivo iniciado em:   $filename  <br>";

$iterator = new DirectoryIterator('E:/xampp/htdocs/LAB/diretorio'); 

foreach ( $iterator as $entry ) {//executa o loop

$nome = $entry->getFilename();//busca o registro com o nome da data
echo "nome:  $nome";
$certo = substr($nome, 0, 8);

if($certo == $filename){
   echo " ---->> O arquivo $certo existe<br>-----------------<br><br>";
   copy($nome, "encerradas/$nome");//faz copia de segurança
   copy("figuraencerrada.jpg", $nome);//copia o arquivo padrao
    echo " Arquivo $certo copiado com segurança<br>-----------------<br><br>";
} 
else {
   echo "    Nenhum arquivo foi localizado com o este nome $certo<br>-----------------<br>";
}
}
    
13.01.2016 / 18:58