Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Glob pattern matching the first part of a file name

Tags:

php

glob

In a directory I have filenames like 123X1.jpg, 23X1.jpg, 23X2.jpg, 4123X1.jpg. I need the glob pattern to only get listed files starting with a required string.

For example:

'23X' -> 23X1.jpg, 23X2.jpg
'123X' -> 123X1.jpg

Last part part of the pattern is always an X. The first one is a number.

like image 251
dstonek Avatar asked Feb 17 '23 14:02

dstonek


2 Answers

It's trivial with glob():

print_r(glob('/path/to/23X*.jpg'));
print_r(glob('/path/to/123X*.jpg'));
like image 136
Alix Axel Avatar answered Feb 19 '23 03:02

Alix Axel


You can try RegexIterator

$fi = new FilesystemIterator(__DIR__, FilesystemIterator::SKIP_DOTS);
$regex = new RegexIterator($fi, "/\dX[a-z\d]+/i");

foreach($regex as $file) {
    echo (string) $file, PHP_EOL;
}
like image 35
Baba Avatar answered Feb 19 '23 03:02

Baba