5

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.

dstonek
  • 945
  • 1
  • 20
  • 33

2 Answers2

7

It's trivial with glob():

print_r(glob('/path/to/23X*.jpg'));
print_r(glob('/path/to/123X*.jpg'));
Alix Axel
  • 151,645
  • 95
  • 393
  • 500
  • 1
    @dstonek: Yes, `glob` is powerful enough to even let you do `glob('/*/*/123X*.jpg')` but it'll be way slower of course. – Alix Axel May 11 '13 at 01:36
1

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;
}
Baba
  • 94,024
  • 28
  • 166
  • 217