Select a file by name in PHP

Asked

Viewed 1,134 times

3

Good afternoon, I need help selecting a file by its PHP name. I use the nomenclature 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 someone help with this part of the code?

Thank you, in the waiting

  • 1

    What have you tried? How’s your code now? Where specifically are you having problems?

  • Why not just use strpos no regex, no subtr?

7 answers

2

<?php

$str = '20160111_ALGUMA_COISA';

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

?>

Upshot:

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 file name, cutting from the beginning (position 0) to the index that is found the "_ALGUMA_COISA".

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

substr - Returns a part of a string

In short lines, I "cut" the string what I want, how far it starts to appear what I nay want.

20160111_ALGUMA_COISA

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

  • Can you explain what the code is doing? Preferably in the answer itself.

  • Edited. Take a look, Diego Felipe :)

2


Using function replace()

$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 reach a year with more than 5 houses. The year 9999 is the limit year. But rest assured that no one will care about your code on January 1, 10000.

  • See: http://answall.com/questions/107755/selecionar-um-arquivo-por-parte-do-nome-em-php/108145#comment224937_108145

2

You say the default is "20160111_ALGUMA_COISA"

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

You can use this to get each data:

<?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 wish to make this a "human" date do so:

<?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

?>

2

I don’t understand if you want to fetch the files, or if they are already listed and you want to extract the number ahead.

If you want to extract the number you can use the 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, thus:

<?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 start with numbers you can try using the glob:

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

Documentation:

1

With strstrstr is also possible. http://php.net/manual/en/function.strstr.php

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

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

0

Eduardo You can also do this way

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

 echo $arq1.'<br>';
 echo $arq2;  
  • Good evening Fabio, which differs from the @Inkeliz example?

  • And good looking except I used "Trim" to fix some blank space

  • I think the trim nothing has changed, if it were reading text files where there would be line breaks it would work, not here. It was the same thing as the @Inkeliz response, don’t get me wrong is that it really doesn’t make sense, understand as a constructive criticism of their collaboration on Stack Overflow in English ;)

-1

Very interesting staff the various collaborations, but follow the final code for those who need it (thank you):

$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>";
}
}
  • This is practically the @Danielomine response the only thing you did was to add the code you were already using that you didn’t specify in the question. Understand, we are not a forum we are a Q&A. If Daniel’s answer is correct then you should mark it. Understand as a constructive criticism ;)

Browser other questions tagged

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