What are some alternative approaches to replacing special characters in file names in PHP scripts to avoid unnecessary encoding and decoding operations?

When dealing with special characters in file names in PHP scripts, one alternative approach to avoid unnecessary encoding and decoding operations is to use a whitelist of allowed characters and replace any special characters with a safe alternative. This can simplify the process and reduce the chances of encountering encoding issues.

// Define a whitelist of allowed characters
$allowedChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_';

// Replace special characters with safe alternatives
$filename = preg_replace('/[^'.$allowedChars.']/u', '_', $filename);

// Use the sanitized filename for further processing
echo $filename;