0

i need a regex to search this: $var[prod_menu]

and replace with this: $var['prod_menu']

At the moment my regex make this: $var['rod_men']

My regex:

preg_replace('/\[[^\'](.*)[^\']\]/U', '['$1']', $input_lines);

Where is the error?

1
  • 1
    There is no code here that adds _ before var. What code have you really got? Commented Nov 6, 2019 at 19:15

2 Answers 2

1

You should start the capturing group after the opening [ and close before the ]

Note that this part in your pattern [^\'](.*)[^\'] uses 2 times a negated character class which actually expects a minimum of 2 characters.

Another way to write your pattern could be using a negated character class matching not [, ], $ or a '

\[([^]\[$']+)\]

Regex demo

In the replacement use

['$1']

Or make the match more restrictive matching 1+ word characters.

\[(\w+)\]

Regex demo

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

5 Comments

Yes that work but there is another litle problem. It always replaces this $var[$test] to $var['$test']
@MarkusHH What is the expected outcome? You could also match 1+ word chars to make the match more specific \[(\w+)\] See regex101.com/r/TL4QyL/1
$var[$test] should stay $var[$test], only replace if string in brackets
@MarkusHH Or exclude the dollar sign from the match \[([^]\[$']+)\] See regex101.com/r/n7Ttjt/1
[(\w+)] That's it!! Thank your very much.
1

Just change your capture group to include the extra chars at the start and end...

preg_replace('/\[([^\'].*[^\'])\]/U', "['$1']", $input_lines);

(I've also fixed the problem with quotes in '['$1']').

1 Comment

This will not work if the keys is less than 3 character long (i.e. array[i])

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.