Generate file name including german umlauts in PHP
I build a download for a file where the filename is not the original one but should be dependent on the project name. But those projects contains special characters, so I needed a smarter function then just "remove spaces".
I came up with the following:
public function sanitizeFileName(string $fileName): string
{
// Remove multiple spaces
$fileName = preg_replace('/\s+/', ' ', $fileName);
// Replace spaces with hyphens
$fileName = preg_replace('/\s/', '-', $fileName);
// Replace german characters
$germanReplaceMap = [
'ä' => 'ae',
'Ä' => 'Ae',
'ü' => 'ue',
'Ü' => 'Ue',
'ö' => 'oe',
'Ö' => 'Oe',
'ß' => 'ss',
];
$fileName = str_replace(array_keys($germanReplaceMap), $germanReplaceMap, $fileName);
// Remove everything but "normal" characters
$fileName = preg_replace("([^\w\s\d\-])", '', $fileName);
// Remove multiple hyphens because of contract and project name connection
$fileName = preg_replace('/-+/', '-', $fileName);
return $fileName;
}
I tried multiple options to replace the german characters like iconv
, mb_convert_encoding
and more. But with none of those I got the result I wished for. If you know a smarter version that works: Let me know :)