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:
What have you tried? How’s your code now? Where specifically are you having problems?
– Marco Aurélio Deleu
Why not just use
strpos
no regex, no subtr?– Pedro Erick