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.

是否可以使用php glob函数匹配任意数量的数字? 我正在尝试匹配图像缩略图的文件名,最终尺寸从2到4位。 p>

我知道我可以提供一个数字范围,但这只匹配一个字符: p>

  glob(“thumbname- [0-  9]  -  [0-9] .jpg“)
  code>  pre> 
 
 

这将匹配thumbname-1-1.jpg但不匹配thumbname-10-10.jpg等 。 p> div>

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

I made a test and it works for me.

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
);

You could split the numbers into different glob arrays and merge them.

For example first you take all images from 0-9 into one array:

$g1 =  glob('thumbname-[0-9].jpg');

After that you create another array which holds the numbers from 10 - 99:

$g2 =  glob('thumbname-[0-9][0-9].jpg');

Now you merge those 2 arrays into one and get all from 0-99:

$gResult = array_merge($g1, $g2);

You can extent it as much as you want just add a [0-9]