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;
}
?>
November 16th, 2005 at 7:01 pm
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);
}
November 16th, 2005 at 10:29 pm
Thanks for sharing!