I am trying to use regex pattern to search for files.
Directory path is:
$css_dir = MY_PLUGIN_DIR.'/source/css/';
Css filename starts with:
$css_prefix = 'hap_css_';
and ends with:
'.css'
With some amount of unknown characters in between.
I dont know how to construct regex pattern with variable and how to construct file exist with regex.
Thank you!
You can use glob():
$files = glob($css_dir . $css_prefix . '*.css');
However, you have to roll your own DirectoryIterator based solution for more complex filtering:
$dir = new DirectoryIterator($css_dir);
$pattern = '/^' . preg_quote($css_prefix) . '.+\\.css$' . '/';
foreach ($dir as $fileInfo) {
if (preg_match($pattern, $fileInfo->getBaseName())) {
// match!
}
}
(One could also integrate a RegexIterator):
The use of scandir() is possible as well:
$pattern = '/^' . preq_quote($css_prefix) . '.+\\.css$' . '/';
$files = array_filter(scandir($css_dir), function ($filename) {
return preg_match($pattern, $filename);
});