The WordPress function sanitize_file_name() is a good way for WordPress developers to, well, sanitize a filename. It’s, probably, the preferred way of sanitizing filenames in the WordPress ecosystem. The function uses a number of underlying functions and constructs, and as with most WordPress functions, it makes use of filters.
By using filters, the behavior of many WordPress functions can be altered to suit your needs.
In my particular use case, I found out that files ending with the extension .min.css and .min.js would not sanitize correctly. Instead, the function would create filenames like this my-custom.min_.css
So, filters to the rescue:
function allow_min_css_extension( array $mime_types ) : array {
// because of how it's parsed, ['min.css'] does not work here
$mime_types['min'] = 'text/css';
return( $mime_types );
}
add_filter( 'mime_types', 'allow_min_css_extension', 10, 1 );
$my_filename = sanitize_file_name( wp_unslash( ( $my_filename ) ) );
remove_filter( 'mime_types', 'docsmatter_allow_min_css_extension', 10, 1 );