What are best practices for validating user input in PHP to prevent special characters and umlauts in file names?

When validating user input in PHP to prevent special characters and umlauts in file names, it is important to use regular expressions to check for unwanted characters and sanitize the input. One approach is to allow only alphanumeric characters, dashes, and underscores in the file name. You can achieve this by using the preg_replace function to remove any characters that are not allowed.

// Validate and sanitize user input for file name
$filename = $_POST['filename'];

// Remove special characters and umlauts from file name
$filename = preg_replace("/[^a-zA-Z0-9-_\.]/", "", $filename);

// Now $filename contains only alphanumeric characters, dashes, underscores, and dots