Are there any potential pitfalls or limitations when using regular expressions in PHP for file pattern matching?

One potential pitfall when using regular expressions in PHP for file pattern matching is that the regex pattern may not be optimized for the specific task, leading to slower performance. To solve this, it's important to carefully craft the regex pattern to match the desired file names efficiently.

$directory = '/path/to/directory/';
$files = scandir($directory);

$pattern = '/^file\d+\.txt$/'; // Example regex pattern to match files like file1.txt, file2.txt, etc.

foreach ($files as $file) {
    if (preg_match($pattern, $file)) {
        echo "Match found: $file\n";
    }
}