0

To skip the explanation & get to the actual question, jump to below the horizontal line.

PHP variables must start with a $ dollar sign; e.g $my_array

PHP arrays are indexed by scalars (like a C++ STL map or a Python dictionary (and similar to JSON)); e.g $my_array[0] or $my_array[$my_val], or, with strings, $my_array['abc'] (single quote, or $my_array["abc"} (double quote).

I have some inherited code which does not quote the string index : $my_array[abc]. That was allowed in previous versions of PHP, but is now causing me problems.


So, I am seeking a reg ex to find an open square bracket [ followed by a character (a .. z, A ... Z); alternatively, followed by not a digit or dollar sign, whichever is easier.


Astute PHP coders will have seen that I can DEFINE(abc, 'abc') and use $my_array[abc], but that's an outlier & I will handle it manually.

Phil
  • 157,677
  • 23
  • 242
  • 245
Mawg says reinstate Monica
  • 38,334
  • 103
  • 306
  • 551
  • 1
    Please show us clear input along with the output you are trying to match. – Tim Biegeleisen Nov 27 '19 at 06:48
  • 1
    FYI, string array indices / keys are allowed if used within a string, eg `echo "$my_array[abc]";`. If your arrays are being used like this, you don't actually have to change anything – Phil Nov 27 '19 at 06:56
  • 1
    They are not; as I stated, that is ths problem. ANd, @TimBiegeleisen, I do give an example : `$my_array[abc]` – Mawg says reinstate Monica Nov 27 '19 at 06:58
  • Have a read of https://stackoverflow.com/questions/4738850/interpolation-double-quoted-string-of-associative-arrays-in-php which shows what @Phil means. – Nigel Ren Nov 27 '19 at 07:02
  • @NigelRen I think OP's _"they are not"_ response means the arrays are not used within strings and as such, are causing `E_NOTICE` warnings for undefined constants – Phil Nov 27 '19 at 07:03
  • I know what he means, and believe that I have addressed his comment in my question. – Mawg says reinstate Monica Nov 27 '19 at 07:04
  • Sorry, but I'm not sure if it is clear in the original question, and I wanted to ensure that if future readers of the question who want to use this solution are aware of the things they need to be aware of when using any solution. – Nigel Ren Nov 27 '19 at 07:09

1 Answers1

2

You should be able to use something like this:

/(?<varname>\$[a-z_]\w*) \s*\[\s* (?<index>[a-z_]\w*) \s*\]/ix

This matches a variable name followed by a square bracket followed by a valid index, ignoring spaces along the way.

You can easily omit the beginning of the pattern if you don't want the variable name to be part of it (in case you're doing this as well with functions' return values or anything else).

Demo: https://regex101.com/r/8hbxs9/6

Jeto
  • 14,596
  • 2
  • 32
  • 46