Oliver O'Neill
Oliver O'Neill

Reputation: 1254

Find/Replace string that doesn't contain quotes

I have inherited a rather large/ugly php codebase (language is unimportant, this is a generic vim question) , where nothing is quoted properly (old php doesn't mind, but new php versions throw warnings).

I'd like to turn $something[somekey] into $something['somekey'], only if its not already quoted or contain the character $

I was trying to build a regular expression to quote the keys, but just cant seem to be able get it to cooperate.

This is what i have so far, which doesn't work but maybe will help explain my question better. And to show that i have actually tried.

:%s/\v\$(.{-})\[(['"$]@<!.{-})\]/$\1['\2']/

My goal is to have something like this:

$something[somekey]            = $something['somekey']
$somethingelse[someotherthing] = $something['someotherthing']
$another['key']                = $another['key'] (is ignored)
$yetanother["keykey"]          = $yetanother["keykey"] (is ignored)
$derp[$herp]                   = $derp[$herp] (is ignored)
$array[3]                      = $array[3] (is ignored)

These can appear anywhere in text, even multiple on the same line, and even touching each other like $something[key]$something[key2], which i would like to be replaced with $something['key']$something['key2']

Another problem, there seems to be random javascript arrays in some files.. which have [] square brackets. So the regex needs to check to see if it starts with $ and text before the brackets.

Im probably asking for the impossible, but any help on this would be great before i go insane editing each file one by one manually.

EDIT: forgot that keys can be numeric, and shouldn't be quoted.

Upvotes: 0

Views: 80

Answers (1)

blackbird
blackbird

Reputation: 967

I tried the following, which processed everything from your question correctly:

:%s/\[\(\I\i*\)\]/['\1']/g

Or, with optional white spaces inside the parens:

:%s/\[\s*\(\I\i*\)\s*\]/['\1']/g

And also checking for $identifier before the parens:

:%s/\(\$\i\+\)\[\s*\(\I\i*\)\s*\]/\1['\2']/g

Upvotes: 2

Related Questions