Search code examples
phphtmlcharacter-encoding

Is there any built-in PHP-function to replace German "Umlaute"?


I have to replace Html-represantation of German "Umlaute" in php-code I do this like this:

Private function replaceHTMLEntities(&$str){
$str = str_replace('Ä',chr(196),$str); 
    $str = str_replace('Ö',chr(214),$str);
    $str = str_replace('Ü',chr(220),$str); 
    $str = str_replace('ä',chr(228),$str);
    $str = str_replace('ö',chr(246),$str);
    $str = str_replace('ü',chr(252),$str);
    $str = str_replace('ß',chr(223),$str);
}

Is there any inbuild-function in php to shorten this code?


Solution

  • I'm not sure about build-in function for this but at least you can reduce and optimize you code using str_replace with parameters as arrays:

    private function replaceHTMLEntities(&$str){
        $search  = ['Ä', 'Ö', 'Ü']; // and others...
        $replace = [chr(196), chr(214), chr(220)]; // and others...
    
        $str = str_replace($search, $replace, $str);
    }
    

    Hint: do not use passing by reference if it is possible. It's harder to debug and changes are not obvious.