Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

help with glob pattern

Tags:

php

glob

It would be nice if someone could give me a regexp pattern for glob for getting below filenames:

1.jpg // this file
1_thumb.jpg
2.png // this file
2_thumb.png
etc...

returning the files without "_thumb". I have this pattern:

$numericalFiles = glob("$this->path/*_thumb.*");

and that give me all with "_thumb."

like image 231
ajsie Avatar asked Jan 18 '10 06:01

ajsie


People also ask

How do glob patterns work?

In computer programming, glob (/ɡlɑːb/) patterns specify sets of filenames with wildcard characters. For example, the Unix Bash shell command mv *. txt textfiles/ moves ( mv ) all files with names ending in . txt from the current directory to the directory textfiles .

Does glob use regex?

The pattern rules for glob are not regular expressions. Instead, they follow standard Unix path expansion rules. There are only a few special characters: two different wild-cards, and character ranges are supported.

What is a glob search?

glob (short for global) is used to return all file paths that match a specific pattern. We can use glob to search for a specific file pattern, or perhaps more usefully, search for files where the filename matches a certain pattern by using wildcard characters.

Can globbing patterns be applied to contents of a file?

You can use different types of globbing patterns for searching particular content from a file. 'grep' command is used for content searching in bash.


2 Answers

glob() isn't the greatest at handling situations where you have complex requirements for file matching, as you've clearly noticed. I'd recommend using PHP's SPL library and taking advantage of the DirectoryIterator class.

$iterator = new DirectoryIterator("/dir/path");
foreach ($iterator as $file) {
    if ($file->isFile() && preg_match("/^[0-9]+\./i",$file->getFilename())) {
        echo $file->getFilename();
    }
}

You can modify your criteria cleanly during the iteration (also, it's easy to modify the iterator if you ever needed recursive directory iteration).

like image 169
zombat Avatar answered Oct 13 '22 06:10

zombat


Glob patterns and regular expressions are different. But PHP's glob implementation does not implement the pattern negation required for matching just those files. You will need to use a larger positive pattern such as [0-9]*.jpg and then filter the results afterwards.

like image 41
Ignacio Vazquez-Abrams Avatar answered Oct 13 '22 05:10

Ignacio Vazquez-Abrams