0

I'm reviewing a my old php software and I need to do some general corrections. I'm trying to do some of them automatically by regex, but in some cases without success. I use Netbeans.

I need to substitute all:

$line[word_test]

with

$line['word_test']

excluding the case where word_test is a var (i.e. $abc) or a number or contains the string "const"

I tried with several regex like

\$line\[[^'|\$|constan](.*)\]

but without success. I need both the regex to write in the "Containing Text" field and that one to write in "Replace with" field of Netbeans replace functionality.

1 Answer 1

2

One option is to use capturing group with a negative lookahead.

(\$line\[)(?!\d|\$\w|[^\]]*const)([^\]]+)(\])

Explanation

  • (\$line\[) Capture group 1, match $line[
  • (?! Negative lookahead, assert what is directly to the right is not
    • \d|\$\w|[^\]]*const Match either a digit, $ followed by a word char or const
  • ) Close lookahead
  • ([^\]]+) Capture group 2, match any char except ]
  • (\]) Capture group 3, match ]

Regex demo

In the replacement use the 3 capturing groups

$1'$2'$3

In case there is an already existing format of $line['word_test1'] as @Nigel Ren points out in the comment, you could extend the negative lookahead:

(\$line\[)(?!'.*?'\]|\d|\$\w|[^\]]*const)([^\]]+)(])

Regex demo

Sign up to request clarification or add additional context in comments.

2 Comments

Not sure if the code needs to cope with ignoring any existing $line['word_test1'] strings in the code.
@NigelRen That is a good point, I will add an update for that case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.