Dédé Lateur
Dédé Lateur

Reputation: 55

String replacement function with Powershell

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 !

Upvotes: 3

Views: 146

Answers (2)

k7s5a
k7s5a

Reputation: 1377

I would prefer to use a hashtable for the [Key - Value] mapping.

$replaceMe = 'I like %1%, %2%, %3%, %4% and %5%'

$keyValueMap = @{
  '%1%' = 'Jägermeister'; 
  '%2%' = 'My wife'; 
  '%3%' = 'PowerShell'; 
  '%4%' = 'the moon';
  '%5%' = 'Hashtable performance'
}

$keyValueMap.GetEnumerator() | % {$replaceMe = $replaceMe -replace $_.key, $_.value }
Write-host $replaceMe 

If I want to compare data structures in PowerShell I wouldn't work with arrays.

In .NET arrays are immutable. Every time you add a new item, the system rebuilds the array and appends the new data.

With each new item your array will gets slower and slower.

Upvotes: 1

Esperento57
Esperento57

Reputation: 17492

try Something like this (en passant j'adore ton pseudo )

$source="I like {0} and {1} !"
$terms=@("coding","drinking beer")
$new=$source -f $terms
$new

Upvotes: 2

Related Questions