How can regular expressions be used to filter out files when using the scandir function in PHP?

Regular expressions can be used with the scandir function in PHP by iterating over the array of files returned by scandir and using preg_match to filter out files based on a specific pattern defined by the regular expression. This allows for more precise filtering of files based on their names or extensions.

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

foreach ($files as $file) {
    if (preg_match('/\.txt$/', $file)) {
        echo $file . "\n";
    }
}