Nikita 웃
Nikita 웃

Reputation: 2060

RegEx - Match all unquoted strings in brackets except if they are all capital-letters

In PHP 7.2, the manual says:

Unquoted strings that are non-existent global constants are taken to be strings of themselves. This behaviour used to emit an E_NOTICE, but will now emit an E_WARNING. In the next major version of PHP, an Error exception will be thrown instead.

Also, code like this $list[products_name], will now produce this warning:

Warning: Use of undefined constant products_name - assumed 'products_name' (this will throw an Error in a future version of PHP) in %s on line %d

I have now switched to PHP 7.2 and got such code that I would like to search and replace, by matching all unqoted strings inside brackets and add single-quotes to them (eg. $list[products_name] will become $list['products_name']), except for strings that are all capital. The reason I want to skip those specifically is because many times they are indeed constants and I shouldn't put them inside quotes. I am new to regex and tried several options. So far, I have come up with this regex:

\$\w+\[([a-zA-Z_]+[\w]+)\]

It works well for most purposes I need it, except it still captures all capital strings in code blocks like this:

$options[$list[_option_id]][]=array($list[_value],$list[_value_id]);
      $option_names[$list[_option_id1]]=$list[_option];
      $product_name=$list[products_name];
$product_name=$list[0];
$product_name=$list[DONTCAPTUREME];
$product_name=$list[CapTureMe];
$product_name=$list[CapTurEME];

DEMO

How can I modify it to not match only examples like DONTCAPTUREME?

Thank you

Upvotes: 1

Views: 831

Answers (2)

Nikita 웃
Nikita 웃

Reputation: 2060

Finally the solution that worked best for me (using grepWin) is:

Search (case sensitive must be enabled):

(").*?\1(*SKIP)(*FAIL)|\$\w+\]?\[(?!\w*\(|\w*:)(?=[^\]]*[a-z])(\K[a-zA-Z_]+[\w]+)

Replace with:

'\2' 

Always backup your files before such operation.

DEMO

Screenshot Here

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370979

Right after the first \[, use negative lookahead for all-caps followed by \]:

\$\w+\[(?![A-Z]+\])([a-zA-Z_]+[\w]+)\]
       ^^^^^^^^^^^^

https://regex101.com/r/I91TNn/3

Upvotes: 3

Related Questions