Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 !

like image 952
Dédé Lateur Avatar asked Jul 18 '26 22:07

Dédé Lateur


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
like image 180
Esperento57 Avatar answered Jul 21 '26 13:07

Esperento57


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.

like image 22
k7s5a Avatar answered Jul 21 '26 13:07

k7s5a