Remove Special Characters From Uploaded Files

This is probably more practical if you deal with a lot of special characters, perhaps in foreign languages. But if you want to make sure particular characters are removed from file name when uploaded, you can. As always, WordPress makes this easy.

add_filter( 'sanitize_file_name_chars', 'add_chars_to_filter', 10, 2 );
function add_chars_to_filter ( $special_chars, $filename_raw ) {
	$special_chars[] = 'e';
	return $special_chars;
}

This particular is example is useless as-is, unless you have something against our favorite vowel ‘e.’

7 thoughts on “Remove Special Characters From Uploaded Files”

  1. Hi I just found this post when searching for a solution to remove special characters from image uploads in WordPress, and I wanted to ask you what I would need to do to remove a string a characters like “é ó æ ð ö í ý ú” etc. 🙂

    Thanks in advance

    1. To remove all those characters, you can merge them with the $special_chars array like this:
      add_filter( ‘sanitize_file_name_chars’, ‘add_chars_to_filter’, 10, 2 );
      function add_chars_to_filter ( $special_chars, $filename_raw ) {
      $chars = array(‘é’, ‘ó’, ‘æ’, ‘ð’, ‘ö’, ‘í’, ‘ý’, ‘ú’);
      $special_chars = array_merge( $special_chars, $chars );
      return $special_chars;
      }

      If you want to remove a pattern of letters/phrase/word, just put that where the single letters are:
      add_filter( ‘sanitize_file_name_chars’, ‘add_chars_to_filter’, 10, 2 );
      function add_chars_to_filter ( $special_chars, $filename_raw ) {
      $chars = array(‘bad_word’);
      $special_chars = array_merge( $special_chars, $chars );
      return $special_chars;
      }

  2. One more question 🙂 Would it be possible to have this code replace letters, that is for example, that ó becomes o and æ becomes ae etc. ?

    1. It may be possible, but unfortunately it’s not something I’ve dealt with yet. The code snippet above doesn’t allow for special ‘replacement’ rule – only removal.
      I may look into it for a future snippet.

      1. No problem, thank you again for your help and for your time. The above snippet is helping me a great deal 🙂

Leave a Reply to Fannar Cancel reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: