Glob-like File and Pattern Matching Utilities for PHP

Packages

March 25th, 2022

Glob-like File and Pattern Matching Utilities for PHP

Splat is a PHP utility by Chris Kankiewicz that provides glob-like file and pattern matching. With this utility, you can convert patterns (see the README) into regular expressions using the provided Pattern instance:

// Returns '#^foo$#'
Pattern::make('foo')->toRegex();
 
// Returns '#^foo/bar\.txt$#'
Pattern::make('foo/bar.txt')->toRegex();
 
// Returns '#^file\.(yml|yaml)$#'
Pattern::make('file.{yml,yaml}')->toRegex();
 
// You can control line anchors as well
 
// Returns '#foo#'
Pattern::make('foo')->toRegex(Glob::NO_ANCHORS);
// Returns '#^foo#'
Pattern::make('foo')->toRegex(Glob::START_ANCHOR);
// Returns '#^foo$#'
Pattern::make('foo')->toRegex(Glob::BOTH_ANCHORS);

This package also includes file glob utilities to get a list of files matching a file glob pattern.

// Get a list of files in a directory (Returns a Symfony Finder Component)
Glob::in('**.txt', 'some/file/path');
 
Glob::matchStart('foo/*', 'foo/bar.txt'); // true
Glob::matchStart('foo/*', 'bar/foo.txt'); // false
Glob::matchEnd('**.txt', 'foo/bar.txt'); // true
Glob::matchEnd('**.txt', 'foo/bar.log'); // false
 
// Filter and reject array of filenames
 
// Returns ['foo.txt', 'foo/bar.txt']
Glob::filter('**.txt', [
'foo', 'foo.txt', 'bar.zip', 'foo/bar.png', 'foo/bar.txt',
]);
 
// Returns ['foo', 'bar.zip', 'foo/bar.png']
Glob::reject('**.txt', [
'foo', 'foo.txt', 'bar.zip', 'foo/bar.png', 'foo/bar.txt',
]);

You can learn more about this package, get full installation instructions, and view the source code on GitHub.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.