I'm working on a large codebase that doesn't have quotes around any array keys, e.g. $_GET[page]
.
Does anyone have a script/regex that programmatically adds quotes to array keys for PHP?
update
Here's what I ended up doing:
egrep -lRZ "\.php" . | \
xargs -0 -l sed -i -e "s/\$\([a-zA-Z_]\+\)\[\([a-zA-Z_]\+\)\]/$\1['\2']/g"
This only handles one-dimensional arrays.
I hated doing this in the past. This will cover all but severe edge cases and multidimentional arrays. Either use preg_replace
or something that allows regex for mass replace in all files (like Dreamweaver).
\$(\w+)\[(\w+)\]
Replace like so (\#
, where #
is the match offset):
$\1['\2']
I believe Dreamweaver's replace syntax is:
$$1['$2']
Multidimentional might work with (after you run the above):
\['(\w+)'\]\[(\w+)\]
['$1']['$2']
And finally, inspired by @MarcB's comment, in theory you could use PHP::Tokenizer. See the example and change the case statment to trigger on T_ARRAY
and alter the array to conform before outputting it (and every other part of the file). If all works well, you'd get a new file, which you could then loop into SPL::DirectoryIterator
and update all files in one go (now and in the future).