SpecialK
SpecialK

Reputation: 108

Replace with regular expression (leave middle text)

I have a site where I need to replace almost 400 of these kind of strings (across dozens or hundreds of files)

$_POST['some_text_here']

with this

mysql_real_escape_string($_POST['some_text_here'])

The key here is that I want to add the ending parenthesis as well or otherwise this would be a trivial search and replace.

I am new to regular expressions so I dont even know if a search and replace is possible while leaving text (specifically the 'some_text_here') in the middle of the replace.

I am using PHPStorm for this if that makes a difference.

Upvotes: 0

Views: 1234

Answers (2)

JDB
JDB

Reputation: 25855

Something like this should work:

(\$_POST\['[^']*'\])

Then replace with something like this

mysql_real_escape_string($1)

Code:

preg_replace ( '($_POST\\[\'[^\']\'\\])', 'mysql_real_escape_string($1)', 'file contents go here' )

Not tested

Upvotes: 1

Philipp
Philipp

Reputation: 15629

I think, regex isn't what you want.. you rather want something like this:

foreach ($_POST as $key => $value) {
    $_POST[$key] = mysql_real_escape_string($value);
}

RegEx..

\$_POST\['([a-zA-Z0-9_-]+)'\]

Replace - something like this:

mysql_real_escape_string\(\$_POST\['$1'\]\)

Btw: mysql_* is deprecated and shouldn't used anymore - use mysqli_ or PDO instead

Upvotes: 0

Related Questions