views:

165

answers:

2

Hello,

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"}
+1  A: 

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")
  }

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

stej
I think you want `Where-Object {!$_.PSIsContainer}` and that it is definitely a better way to go IMO (vs testing the Attributes).
Keith Hill
@Keith, my mistake. Thx :)
stej
A: 

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.

Keith Hill