Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php glob pattern match for arbitray number of digits

Tags:

php

glob

Is it possible to match an arbitrary number of digits with the php glob function? I'm trying to match file names for image thumbnails that end with dimensions ranging from two to four digits.

I know I can supply a digit range, but this only matches a single character:

glob("thumbname-[0-9]-[0-9].jpg")

This will match thumbname-1-1.jpg but not thumbname-10-10.jpg, etc.

like image 320
baseten Avatar asked Jan 24 '13 16:01

baseten


People also ask

What is glob() in php?

The glob() function returns an array of filenames or directories matching a specified pattern.

What is glob regex?

Regex and Glob patterns are similar ways of matching patterns in strings. The main difference is that the regex pattern matches strings in code, while globbing matches file names or file content in the terminal. Globbing is the shell's way of providing regular expression patterns like other programming languages.


2 Answers

Try using: glob("thumbname-[0-9]*-[0-9]*.jpg")

I made a test and it works for me.

like image 127
m4t1t0 Avatar answered Oct 23 '22 17:10

m4t1t0


Alternative to glob(), using recursiveDirectoryIterator with a regexp

$Directory = new RecursiveDirectoryIterator('path/to/project/');
$Iterator = new RecursiveIteratorIterator($Directory);
$Regex = new RegexIterator($Iterator,
    '/^thumbname-[0-9]*-[0-9]*\.jpg$/i', 
    RecursiveRegexIterator::GET_MATCH
);
like image 4
Mark Baker Avatar answered Oct 23 '22 16:10

Mark Baker