What are best practices for handling file names with spaces or special characters in PHP applications?

When handling file names with spaces or special characters in PHP applications, it is important to sanitize and validate the file names to avoid any potential security vulnerabilities or file system errors. One common approach is to use the PHP function `preg_replace()` to replace any unwanted characters with a safe alternative, such as underscores or dashes.

// Sanitize and validate file name
function sanitizeFileName($fileName) {
    // Replace spaces and special characters with underscores
    $sanitizedFileName = preg_replace('/[^\w\-\.]/', '_', $fileName);
    
    return $sanitizedFileName;
}

// Example usage
$fileName = "my file!@#name.jpg";
$sanitizedFileName = sanitizeFileName($fileName);
echo $sanitizedFileName; // Output: my_file_name.jpg