简体   繁体   中英

Replace a repeating pattern using regex

I want to replace all non quoted array keys in my source code :

$array[keyValue]

with quoted array keys:

$array['keyValue']

For single dimension arrays this regexp allows me to do this :

preg_replace('/\$([a-z-_0-9]+)(\[([a-z][a-zA-Z-_0-9]+)\])+/', '\$$1['$3']', $input_lines);

test : https://www.phpliveregex.com/p/pXc

Note all my keys start with a lower case letter.

My problem comes when I have multi dimension arrays and I want to change:

$array[keyValue1][keyValue2]

to :

$array['keyValue1']['keyValue2']

or even

$array[keyValue1]...[keyValueN]

to

$array['keyValue1']...['keyValueN']

for larger dimension-ed arrays. Any attempt I make to match the pattern multiple times ends up matching between the first opening bracket [ and the last one ] as one match.

Edit: Reason for doing this is to avoid errors and notices like this

E_NOTICE : type 8 -- Use of undefined constant key - assumed 'key' -- at line 2 

in my logs

Note: take care of predefined constants. This doesn't and can't ignore them.

You are in need of a continuous match using \\G . Use preg_replace with the following regex:

(\$\w+\[|\G(?!\A)\[)([^]['"]+)\]

and put the following string as the substitution string:

$1'$2']

See live demo here

PHP code:

preg_replace('~(\$\w+\[|\G(?!\A)\[)([^][\'"]+)\]~', '$1\'$2\']', $str);

Regex break down:

  • ( Start of capturing group #1
    • \\$\\w+\\[ Match a $ then some word characters then an opening bracket
    • | Or
    • \\G(?!\\A) Start match from where previous match ends
    • \\[ Match an opening bracket
  • ) End of capturing group #1
  • ( Start of capturing group #2
    • [^]['"]+ Match anything but [ , ] , ' and "
  • ) End of capturing group #2
  • \\] Match a closing bracket

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM