What are the security considerations when using regular expressions to filter file names in PHP?

When using regular expressions to filter file names in PHP, it's important to consider security implications such as preventing directory traversal attacks. To mitigate this risk, it's recommended to use a whitelist approach where only allowed characters are permitted in the file names.

// Example of using a whitelist approach to filter file names
$filename = "example_file.jpg";

// Define a regular expression pattern to only allow alphanumeric characters, underscores, and periods
$pattern = '/^[a-zA-Z0-9_.-]+$/';

if (preg_match($pattern, $filename)) {
    // File name is valid
    echo "File name is valid!";
} else {
    // File name contains disallowed characters
    echo "File name is invalid!";
}