Find all text in square brackets with regex
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.
source to share
If a sed allowed to just do:
sed -i "s/(\$[^[]*[)([^]]*)]/\1'\2']/g" file
Explanation:
-
sed "s/pattern/replace/g"
is a commandsed
that looks for a pattern and replaces it with a replacement. Parametersg
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 find, 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
.
source to share