4

I am using a regular expression search to match up and replace some text. The text can span multiple lines (may or may not have line breaks). Currently I have this:

 $regex = "\<\?php eval.*?\>"

Get-ChildItem -exclude *.bak | Where-Object {$_.Attributes -ne "Directory"} |ForEach-Object {
 $text = [string]::Join("`n", (Get-Content $_))
 $text -replace $RegEx ,"REPLACED"}

3 Answers 3

5

Try this:

$regex = New-Object Text.RegularExpressions.Regex "\<\?php eval.*?\>", ('singleline', 'multiline')

Get-ChildItem -exclude *.bak |
  Where-Object {!$_.PsIsContainer} |
  ForEach-Object {
     $text = (Get-Content $_.FullName) -join "`n"
     $regex.Replace($text, "REPLACED")
  }

A regular expression is explicitly created via New-Object so that options can be passed in.

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

1 Comment

I think you want Where-Object {!$_.PSIsContainer} and that it is definitely a better way to go IMO (vs testing the Attributes).
1

Try changing your regex pattern to:

 "(?s)\<\?php eval.*?\>"

to get singleline (dot matches any char including line terminators). Since you aren't using the ^ or $ metacharacters I don't think you need to specify multiline (^ & $ match embedded line terminators).

Update: It seems that -replace makes sure the regex is case-insensitive so the i option isn't needed.

Comments

0

One should use the (.|\n)+ expression to cross line boundaries since . doesn't match new lines.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.