Max Lindner
Max Lindner

Reputation: 211

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?

Upvotes: 1

Views: 928

Answers (2)

Isaac Hatilima
Isaac Hatilima

Reputation: 213

Better Late than never. This what worked for me.

$inputString2 = "Schöner Graben Straße. Gülpät Älbeg Ürh Örder ";
function replaceHTMLEntities($str)
{
    $str = str_replace('Ä', 'Ae', $str);
    $str = str_replace('ä', 'ae', $str);
    $str = str_replace('Ö', 'Oe', $str);
    $str = str_replace('ö', 'oe', $str);
    $str = str_replace('Ü', 'Ue', $str);
    $str = str_replace('ü', 'ue', $str);
    $str = str_replace('ß', 'ss', $str);

    return $str;
}

echo replaceHTMLEntities($inputString2);

Upvotes: 0

Slava
Slava

Reputation: 938

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.

Upvotes: 1

Related Questions