Home > Software engineering >  Matching PHP array keys without quotation marks to update old PHP code to modern
Matching PHP array keys without quotation marks to update old PHP code to modern

Time:08-12

Hi I'm currently working with a project in which the following occurs;

$example = $array[key]

instead of

$example = $array['key'] or $example=$array["key"]

I'm trying to use regex to update these old array key strings. I currently have the following;

(\$([a-z0-9_]*)\[(?!('|"))([a-z0-9_]*)(?!('|"))\])

This matches $array[key], but also matches things like this;

  • $array[]

  • $array inside a javascript tag.

The code is also very old and has script tags inside php files, without a framework.

I'm using regex inside Notepad , does anyone think they could write me a regex query to capture non string array keys and avoid $array[], $array[$variable] and $array inside script tags, and replace them with quotes?

Thank you

CodePudding user response:

You can use

Find What: (?s)<script\b[^>]*>.*?</script>(*SKIP)(*F)|\$(\w )\[(?!\d ])(\w )]
Replace With: $$1["$2"]

See the enter image description here

Details:

  • (?s) - now, . matches newnlines
  • <script\b[^>]*> - an open script tag
  • .*? - any zero or more chars as few as possible
  • </script> - closing </script> tag
  • (*SKIP)(*F) - fail the match and go on to search for the next one from the failure position
  • | - or
  • \$ - a $ char
  • (\w ) - Group 1: any one or more word chars
  • \[ - a [ char
  • (?!\d ]) - a negative lookahead that fails the match if there are one or more digits and ] immediately to the right of the current location
  • (\w ) - Group 2: one or more word chars
  • ] - a ] char.

CodePudding user response:

This seem to work fine for me:

\$[a-zA-Z0-9_] \[[a-zA-Z0-9_] \]
  • Related