String replacement function with Powershell

I am desperately trying to adapt the following function from PHP to Powershell:

LgReplace ($ origString, $ repArray) function

{
    // 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 words, the function will look for "% 1%" in $ source, switch to "drink beer", then search for "% 2%" in $ source, replace it with "encoding", then return the result: "I like drinking beer and encode!".

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 to no avail ... Any help would be greatly appreciated! Thank!

+3


source to share


2 answers


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

      

+2


source


I would rather use a hash table to display the [Key-Value].

$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 be working with arrays.



In .NET, arrays are immutable. Each time you add a new element, the system rebuilds the array and adds new data.

With each new element, your array will be slower and slower.

+1


source







All Articles