×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Added: Nov 3, 2017 11:35 PM
Views: 2560
Tags: rename
  1. /**
  2.  * Produces cleaner filenames for uploads
  3.  *
  4.  * @param  string $filename
  5.  * @return string
  6.  */
  7. function wpartisan_sanitize_file_name( $filename ) {
  8.  
  9.     $sanitized_filename = remove_accents( $filename ); // Convert to ASCII
  10.  
  11.     // Standard replacements
  12.     $invalid = array(
  13.         ' '   => '-',
  14.         '%20' => '-',
  15.         '_'   => '-',
  16.     );
  17.     $sanitized_filename = str_replace( array_keys( $invalid ), array_values( $invalid ), $sanitized_filename );
  18.  
  19.     $sanitized_filename = preg_replace('/[^A-Za-z0-9-\. ]/', '', $sanitized_filename); // Remove all non-alphanumeric except .
  20.     $sanitized_filename = preg_replace('/\.(?=.*\.)/', '', $sanitized_filename); // Remove all but last .
  21.     $sanitized_filename = preg_replace('/-+/', '-', $sanitized_filename); // Replace any more than one - in a row
  22.     $sanitized_filename = str_replace('-.', '.', $sanitized_filename); // Remove last - if at the end
  23.     $sanitized_filename = strtolower( $sanitized_filename ); // Lowercase
  24.  
  25.     return $sanitized_filename;
  26. }
  27.  
  28. add_filter( 'sanitize_file_name', 'wpartisan_sanitize_file_name', 10, 1 );