2

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!

2
  • Why not just use hap_css_.+?\.css? Commented Jan 12, 2014 at 16:01
  • I could, but I still need to construct file_exist with regex. Commented Jan 12, 2014 at 18:06

1 Answer 1

6

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);
});
Sign up to request clarification or add additional context in comments.

3 Comments

Can I use glob to detect multiple files?
@Toniq Yes, you can. The documentation says "Returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error."
should be preg_quote not preq_quote

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.