Find multiple lines spanning text and replace them with PowerShell

I use regex search to match and replace some text. Text can span multiple lines (may or may not have line breaks). I currently 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
source share
3 answers

Try the following:

$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 through New-Object so that options can be passed.

+5
source

Try changing the regex pattern to:

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

singleline ( char, ). ^ $, , (^ $ ).

: , -replace , , i .

+1

(.|\n)+ . .

0

Source: https://habr.com/ru/post/1750394/


All Articles