Converting umlaute with symfony String component

There are multiple PHP native ways to convert umlaute and other special characters to ascii save formats, but most of them i experience insufficient in the one or other way.

Since i am using symfony anyway i can use the String component which has a handy slugger which converts any characters into safe ascii characters.
It is very flexible and can be customized with locales, custom replacements and closures.

$umlautString = "Müller Meier"; $slugger = new Symfony\Component\String\Slugger\AsciiSlugger('de'); $slugger->slug($umlautString, $seperator = ' ')->toString(); echo $umlautString; // mueller meier
Code language: PHP (php)

I guess this will become my go-to method resp. slugger to convert umlaute in any PHP application.

One example why the PHP native ways have their downsides is iconv.
Iconv can transliterate umlauts:

$string = iconv('UTF-8', 'ASCII//TRANSLIT', $string);
Code language: PHP (php)

But it can not handle the locale in a convenient way but relies on the system wide locale instead.
You need to use the global method setlocale before using it and reset the locale after usage again, which can cause sideeffects and is not very convenient.


$utf8_sentence = 'Weiß, Göbel'; //transliterate $trans_sentence = iconv('UTF-8', 'ASCII//TRANSLIT', $utf8_sentence); //gives [Weiss, Gobel] //Germany setlocale(LC_ALL, 'de_DE'); $trans_sentence = iconv('UTF-8', 'ASCII//TRANSLIT', $utf8_sentence); //gives [Weiss, Goebel]
Code language: PHP (php)

Thanks to this StackOverflow answer for the tip with the symfony String component.