DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

PHP Filename Bad Character Filter

02.17.2006
| 10820 views |
  • submit to reddit
        // Function to filter out bad characters in a given filename

function replace_bad_filename_chars($filename) {
  $filtered_filename = "";

  $patterns = array(
    "/\s/", # Whitespace
    "/\&/", # Ampersand
    "/\+/"  # Plus
  );
  $replacements = array(
    "_",   # Whitespace
    "and", # Ampersand
    "plus" # Plus
  );
  
  $filename = preg_replace($patterns,$replacements,$filename);
  for ($i=0;$i<strlen($filename);$i++) {
    $current_char = substr($filename,$i,1);
    if (ctype_alnum($current_char) == TRUE || $current_char == "_" || $current_char == ".") {
      $filtered_filename .= $current_char;
    }
  }     
        
  return $filtered_filename;
}