3

I have several php files in directory, I want to replace a few words in all files with different text. It's a part of my code:

$replacements_table=
("hr_table", "tbl_table"),
('$users', "tbl_users")

foreach ($file in $phpFiles){
    foreach($replacement in $replacements_table){
        (Get-Content $file) | Foreach-Object{$_ -replace $replacement} | Set-Content $file 
    }
}

It works fine for replacing "hr_table", but doesn't work at all for '$users'. Any suggestion would be nice

4 Answers 4

4

The string is actually a regular expression and so needs to be escaped using '\'. See this thread

$replacements_table= ("hr_table", "tbl_table"), ('\$users', "tbl_users")

will work.

Sign up to request clarification or add additional context in comments.

1 Comment

No problem. Please accept an answer by clicking the V besides it. This markes the question as answered and gives credit to the person helping. :)
2

The dollar sign is a special regular expression character, matches the end of a string, you need to escape it. Escaping a character in regex is done by a '\' in front of the character you want to escape. A safer method to escape characters (especially when you don't know if the string might contain special characters) is to use the Escape method.

$replacements_table= (hr_table', 'tbl_table'), ([regex]::Escape('$users'), 'tbl_users')

Comments

1

Try escaping "$' with a backslash: '\$users' The $ symbol tells the regular expression to match at the end of the string. The backslash is the regular expression escape character.

Comments

0

try using double quotes around your variable name instead of single quotes

EDIT

Try something along these lines ....

$x = $x.Replace($originalText, '$user')

5 Comments

That would not work, as he wants the string '$users' replaced. Using double quotes would mean that Powershell interprets it a variable.
I also tried "`$users", but it doesn't work either. Any other ideas?
I know when I've wanted the $ to be used (ie - not designating a variable), I've had to put it in single quotes. like so '$' + "$someVariable". But I'm not sure how to approach your problem because you're using the variable containing the $ as a parameter for another function
having said that I've used $_.Replace(origStr, newStr) in some of my script and I've got $ symbols in my newStr. I'll add another answer with an example of the code I used
I also tried "`$users" along with combinations of quotes, but no luck. I would guess Powershell actually reads the variable as '$users' the first time but when it's used in the loop it's already 'unwrapped' from the string and will be interpreted as a variable. Could you try to rewrite it in a more verbose way? Perhaps without using pipes to try to see exactly where it fails and what the replacement variable contains in each step?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.