Find all text in square brackets with regex

I have a problem, because of the PHP version I need to change my code from $array[stringindex]

to$array['stringindex'];

So, I want to find all text using regex and replace them all. How do I find all the lines that look like this? $array[stringindex]

...

+3


source to share


3 answers


It depends on the tool you want to use for the replacement. with sed for example, it would be something like this:



sed "s/\(\$array\)\[\([^]]*\)\]/\1['\2']/g"

      

+1


source


Here's a solution in PHP:

$re = "/(\\$[[:alpha:]][[:alnum:]]+\\[)([[:alpha:]][[:alnum:]]+)(\\])/"; 
$str = "here is \$array[stringindex] but not \$array['stringindex'] nor \$3array[stringindex] nor \$array[4stringindex]"; 
$subst = "$1'$2'$3"; 

$result = preg_replace($re, $subst, $str);

      

You can try it interactively here . I'm looking for variables that start with a letter, otherwise things like $foo[42]

will get converted to $foo['42']

, which might not be desirable.



Please note that all solutions here will not handle every case correctly.

Looking at Sublime Text regex help it would seem like you could just paste (\\$[[:alpha:]][[:alnum:]]+\\[)([[:alpha:]][[:alnum:]]+)(\\])

in the search box and $1'$2'$3

in the Replace box.

+3


source


If a allowed to just do:

sed -i "s/(\$[^[]*[)([^]]*)]/\1'\2']/g" file

      

Explanation:

  • sed "s/pattern/replace/g"

    is a command sed

    that looks for a pattern and replaces it with a replacement. Parameters g

    mean replacing multiple times with a string.
  • (\$[^[]*[)([^]]*)]

    this pattern is in two groups (between brackets). The first is the dollar, followed by a series of symbols [

    . This is followed by an opening square bracket, followed by a series of open brackets, followed by a closing square bracket.
  • \1'\2']

    replacement string: \1

    means to insert the first captured group (same for \2

    ). We mostly end \2

    with quotes (that's what you wanted).
  • The options -i

    mean that the changes must be applied to the original file that comes at the end.

For more information see man sed

.

This can be combined with , in the following way:

find . -name '*.php' -exec sed -i "s/(\$[^[]*[)([^]]*)]/\1'\2']/g" '{}' \;

      

This will apply sed command for all files it finds php

.

+1


source







All Articles