Home > Software design >  How to find only unquoted array indices in PHP variable and quote them, using Notepad ?
How to find only unquoted array indices in PHP variable and quote them, using Notepad ?

Time:11-20

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

CodePudding user response:

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/

  • Related