2

I have code similar to this:

$POST_['%']

where % is any length any letter+numbers string and I want to replace it with

mysql_real_escape_string($POST['%'])

so far I have built up this command but it doesn't recongnise $POST['.'] as any string.

:%s/$_POST['.']/mysql_escape_string($_POST['\=submatch(0)'])/gc

4 Answers 4

2

First, your use of \=submatch(0) is overly-complex, just use \0. And be aware that sub-match 0 is always the fully matched pattern, so your replacement pattern has some redundancy. Second, the . atom only matches one character. And finally, you need to escape the []'s and the $. Try this instead:

:%s/\$_POST\['.\{-}'\]/mysql_escape_string(\0)/gc

The use of \{-} means to match any number of the previous atom, in a non-greedy way (as opposed to *).

I also note that your examples are inconsistent with each other. Is it "$POST_[...]", "$_POST[...]" or just "$POST[...]"?

You may want to take a look at a book like Mastering Regular Expressions.

0
2

$, [ and ] are meta characters in regular expressions. Try this (untested)

:%s/\$_POST\['.'\]/mysql_escape_string(\$_POST\['\=submatch(0)'\])/gc

[edit] Thanks @tink

2
  • Pattern not found: $_POST['.']
    – James
    Dec 17, 2012 at 21:02
  • Actually ... $ is also a special character, so try this: %s/\$POST_['.']/mysql_escape_string($_POST['\=submatch(0)'])/gc
    – tink
    Dec 17, 2012 at 21:16
1
s/^\(.*\)$/mysql_real_escape_string(\1)/

seems to do what you want. It's simple since you're just adding text around the existing string rather than actually replacing things inside it.

3
  • Im failing to rework your post to just replace $POST[''], atm it just replaces all lines with 'mysql_real_escape_string(1)'
    – James
    Dec 17, 2012 at 20:58
  • I tried something like this: :%s/$POST['^(.*)$']/mysql_real_escape_string(\1)/g
    – James
    Dec 17, 2012 at 20:59
  • Our vim's must record backref's differently, then... If nothing else, you can just replace ^ and $ in two replacement runs.
    – John
    Dec 18, 2012 at 13:07
0

8 months on and I need this again so I though I'd provide a neat solution:

sed 's/\$_GET\[\(.*\)\]/mysqli_real_escape_string(\$_GET\[\1\])/g' test.php

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .