How to find only unquoted array indices in PHP variable and quote them, using Notepad++?

0

Issue

Hi I have several lines of code like these:

$row[number];
$row[user];

and I would like to transform them like this:

$row['number'];
$row['user'];

On notepad with Find and Replace using regular expression to find them I used this expression:

\$row\[.*?\]

You know how I could replace the same word by adding: ' ' to the extremes?
Thanks

Solution

You need to look for non quotes in the index notations so replace .*? (which essentially says "anything") with [^']+?. You also can take the PHP definition for a valid variable and us that prior to the index notation to be more exact:

([$][a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)[[]([^']+?)[\]]

you then replace with:

$1['$2']

https://regex101.com/r/GMrMEi/1/

If you wanted to go a step forward you could use a negative lookahead to exclude integers ((?!\d+)) indices (because those are valid in PHP):

([$][a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)[[](?!\d+)([^']+?)[\]]

https://regex101.com/r/bU2sRg/1/

If it is only ever $row you can do:

[$]row[[]([^']+?)[\]]

and

$row['$1']

https://regex101.com/r/tTMmS7/1/

Answered By – user3783243

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More