String replacement function with Powershell

Viewed 119

I'm desesperately trying to adapt the following function from PHP to Powershell :

function lgReplace($origString,$repArray)

{
    // Transforms an input string containing terms like %1%, %2% and so on by values in array
    for($i=1;$i<count($repArray)+1;$i++)
    {
        $origString=str_replace("%$i%",$repArray[$i],$origString);
    }
    return $origString;
}

In php, you can call this function like this :

$source="I like %1% and %2% !";
$new=lgReplace($source, array(1=>"drinking beer",2=>"coding")

In other word, the function will look for "%1%" in $source, change it to "drinking beer", then look for "%2%" in $source, replace it by "coding" then return the result, which is "I like drinking beer and coding !".

I tried to adapt this function to powershell, but failed :

function lgReplace($origString,$repArray)
{
    # Transforms an input string containing terms like %1%, %2% and so on by values in array
    for($i=1;$i -lt $repArray.count+1;$i++)
    {
        $origString=$origString -replace "%$i%",$repArray[$i]
    }
    return $origString
}

$source="I like %1% and %2% !"
$terms=@("coding","drinking beer")
$new=lgReplace $source,$terms
$new

$new displays this :

I like %1% and %2% !
coding
drinking beer

I tried several ways to make this work but to no avail... Any help would be greatly appreciated ! Thanks !

2 Answers
Related