Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

Hi I have several lines of code like these:

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

and I would like to transform them like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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/

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading