Page 1 of 1

Vim regular expression for fixing associative arrays

Posted: Tue Feb 19, 2013 2:47 am
by VelvetMirror
I've been assigned a project that have associative arrays without single quotes all over the place.

Example:

$foo[bar]

Which should be:

$foo['bar']

This generates a PHP notice and it's very bad practice.

With this command in Vim I can replace all "foo" instances with "bar" in the current directory and subdirectories

:args **/*.php | argdo %s/foo/bar/ge | write

I would like to apply the same principle with a regular expression in order to fix the associative arrays.

So instead of 'foo' there should be a regular expression that finds associative array keys and instead of "bar" another regular expression that inserts single quotes.

Any suggestions?

May be this request for help is too difficult or not even possible, in that case I would take any recommendation on how to approach this problem.

Re: Vim regular expression for fixing associative arrays

Posted: Tue Feb 19, 2013 3:14 am
by Weirdan
I'd just use a simple substitution like '[' -> "['", plus manual confirmation of each replace (:help s)

Re: Vim regular expression for fixing associative arrays

Posted: Tue Feb 19, 2013 7:35 am
by VelvetMirror
The problem with that approach is that there are many files with this problem, it could take me a very long time to do this manually.

Furthermore in that way it would also find instances of indexed arrays.

Re: Vim regular expression for fixing associative arrays

Posted: Tue Feb 19, 2013 2:33 pm
by Weirdan
the problem with regex is that it's not really suited for such a task, thus you'd have either accept some false positives
(like arrays with integer indices) or some false negatives. Proper solution (in academic sense) would require you to properly lex php code (which is quite simple thanks to token_get_all() function) and apply some parsing (to support cases like $arr[ind . $otherArr[otherInd]]).