Vim regular expression for fixing associative arrays

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
VelvetMirror
Forum Newbie
Posts: 2
Joined: Tue Feb 19, 2013 2:42 am

Vim regular expression for fixing associative arrays

Post 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.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Vim regular expression for fixing associative arrays

Post by Weirdan »

I'd just use a simple substitution like '[' -> "['", plus manual confirmation of each replace (:help s)
VelvetMirror
Forum Newbie
Posts: 2
Joined: Tue Feb 19, 2013 2:42 am

Re: Vim regular expression for fixing associative arrays

Post 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.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Vim regular expression for fixing associative arrays

Post 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]]).
Post Reply