<?php

/**
 * FileHelper holds a collection of static methods, useful for generic purposes
 *
 */
class FileHelper {

    /**
     * Returns a safe filename by replacing all dangerous characters 
     * with an underscore.
     *
     * @param string $filename The source filename to be "sanitized"
     *
     * @return Boolean string A safe version of the input filename
     */
    public static function sanitizeFileName($filename) {
        // replace non letter or digits by -
        $filename = preg_replace('#[^\\pL\d]+#u', '-', $filename);

        // trim
        $filename = trim($filename, '-');

        // transliterate
        if (function_exists('iconv')) {
            $filename = iconv('utf-8', 'us-ascii//TRANSLIT', $filename);
        }

        // lowercase
        $filename = strtolower($filename);

        // remove unwanted characters
        $filename = preg_replace('#[^-\w]+#', '', $filename);

        if (empty($filename)) {
            return 'n-a';
        }

        return $filename;
    }

}

// usage:
//$safe_filename = FileHelper::sanitizeFileName('#my  unsaf&/file\name?"');
?>;