How can regular expressions be used to match specific file extensions in PHP?

Regular expressions can be used in PHP to match specific file extensions by using the preg_match function. By defining a regular expression pattern that matches the desired file extension, we can then use preg_match to check if a given file path has that extension. This can be useful for filtering or processing files based on their extensions.

$filePath = 'example.txt';
$pattern = '/\.txt$/'; // Regular expression pattern to match .txt file extension

if (preg_match($pattern, $filePath)) {
    echo 'File has a .txt extension';
} else {
    echo 'File does not have a .txt extension';
}