Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
share|improve this question
add comment

4 Answers

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:

:%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.

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

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

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

[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
add comment
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.

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
add comment

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
add comment

Your Answer

 
discard

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.