Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have code similar to this:


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


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

share|improve this question
up vote 2 down vote accepted

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:


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.

share|improve this answer
Thank you! worked perfectly – James Dec 17 '12 at 21:18

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


[edit] Thanks @tink

share|improve this answer
Pattern not found: $_POST['.'] – James Dec 17 '12 at 21:02
Actually ... $ is also a special character, so try this: %s/\$POST_['.']/mysql_escape_string($_POST['\=submatch(0)'])/gc – tink Dec 17 '12 at 21:16

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.

share|improve this answer
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 '12 at 20:58
I tried something like this: :%s/$POST['^(.*)$']/mysql_real_escape_string(\1)/g – James Dec 17 '12 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 '12 at 13:07

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
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.