Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell - How to build a function to replace certain special characters with others

I'm trying to build a function in Powershell that I can use every time I have to replace a list of special characters with other characters. For example, this is the list of the special chars:

$Specialchars = '["ü","ä","ö","ß","æ","Œ","œ","°","~","Ø"]'

And I want that function to replace for example the "ü" with "ue" or the "Ø" with "o" and so on. The idea is to run the function against any string that I want to have those special characters replaced the way I want.

For now, I tried this:

function ReplaceSpecialChars($chars)
{
    return $chars -replace "Ø","o"
    return $chars -replace "~",""
    return $chars -replace "œ","oe"
}

and it works only when it founds the first special characters, the "Ø" and not for example when I run it against a string which has the "~". I'm not an expert of Powershell function at all, so I was wondering if somebody has some hints to help me.

Thanks a lot !

like image 317
Vanni Avatar asked Nov 22 '25 22:11

Vanni


1 Answers

You must assign the result of the replacement before doing the next.

Here is an updated version of the function, incl a way to define your replacements:

function ReplaceSpecialChars([string]$string) {
    # define replacements:
    @{
        "ä" = "ae"
        "ß" =  "ss"
        # ...
    }.GetEnumerator() | foreach {
        $string = $string.Replace($_.Key, $_.Value)
    }
    return $string
}

Note that you might want to define lowercase + uppercase replacements.

like image 105
marsze Avatar answered Nov 25 '25 16:11

marsze