ASPit - Totally ASP JSit - Totally JavaScript
Search PHPit

Use this textbox to search for articles on PHPit. Seperate keywords with a space.

Advertisements

Filename safe

Use this very handy codesnippet to automatically create a filename from a string. It removes all invalid characters and changes them into a ‘_’.

function filename_safe($filename) {
    
$temp $filename;

    
// Lower case
    
$temp strtolower($temp);

    
// Replace spaces with a '_'
    
$temp str_replace(" ""_"$temp);

    
// Loop through string
    
$result '';
    for (
$i=0$i<strlen($temp); $i++) {
        if (
preg_match('([0-9]|[a-z]|_)'$temp[$i])) {
            
$result $result $temp[$i];
        }    
    }

    
// Return filename
    
return $result;
}
?>

2 Responses to “Filename safe”

  1. maxhb Says:

    Hi!
    The following will convert any string to filesystem safe characters and handle german umlauts as well.
    In favor of the above solution this one is faster and more reliable as it e.g. preserves dots within filenames which are usually used to separate filenames and file extensions.

    function safe_filename ($filename) {
    $search = array(
    // Definition of German Umlauts START
    ‘/ß/’,
    ‘/ä/’,'/Ä/’,
    ‘/ö/’,'/Ö/’,
    ‘/ü/’,'/Ü/’,
    // Definition of German Umlauts ENDE
    ‘([^[:alnum:]._])’ // Disallow: Not alphanumeric, dot or underscore
    );
    $replace = array(
    ’ss’,
    ‘ae’,'Ae’,
    ‘oe’,'Oe’,
    ‘ue’,'Ue’,
    ‘_’
    );
    return preg_replace($search,$replace,$filename);
    }

  2. Dennis Pallett Says:

    Thanks for sharing!

Leave a Reply