views:

167

answers:

1

Hello,

I've been trying to find a string in PHP that matches something like this:

Currently I've tried something like this;

<()\?php eval(^>>

but it dosen't seem to get the string correctly.

edit: I forgot to add that I need to grab all the text form "" and it spans multiple lines.

+4  A: 

Why not just use Select-String?

ls *.php | Select-String "<?php eval"

The pattern given to Select-String is read as a regular expression. You can do plain-text matching by specifying the simpleMatch switch:

ls *.php | Select-String "<?php eval" -simpleMatch

Here's the command to get the live help for PowerShell regular expressions:

get-help about_regular_expression

EDIT:

Ah, you didn't specify in your question that you were doing a REPLACE operation. This is a bit different, especially since it spans multiple lines. I would suggest something like this:

# Retrieve file as a single string.
$contents = [string]::Join("`n", $(Get-Content path\to\file.php))

# Now replace.
$replaced = $contents -replace '(?s)(<\?php eval\()(.*?)(\)\?>)', '$1neweval$3'

So what this is doing is looking for <?php eval(, then LAZILY (important!) looking for )?>, all in single-line mode, so newlines are matched in the .*? portion. (Slashes before the question marks and parens to escape them.) It then replaces all matches with group 1 (in this case, <?php eval(), some text, then group 3 (the )?>). You can make the grouping as complex as you need to to collect information from within the match.

Also, because you are trying to use regex to parse a language, instead of a language parser, there are lots of cases where this can go horribly, horribly wrong. Just be aware, and don't clobber your files until you've verified that the output is correct.

jdmichal
My current script was using regex like this:|ForEach-Object { Copy-Item $_ "$($_).bak";(Get-Content $_) -replace $RegEx ,""I will test it using the Select-String commandlet.
MrGrant
This won't work as I need to find a block of text between the opening "<?php eval" and the closing tag "?>" I am replacing this text with some other text. The -select seems to only grab one line but the text spans multiple lines.
MrGrant
I have updated my answer to reflect your comment.
jdmichal