Home » Php » php – Find and replace with regex by defining beginning and end of string

php – Find and replace with regex by defining beginning and end of string

Posted by: admin February 25, 2020 Leave a comment

Questions:

How would I replace in PhpStorm (it is not important I guess) all occurrences of (selecting string which starts with {!! and ends with !!}):

{!! $arr['my.key.1234'] !!}
to {!! $arr('my.key.1234') !!}
(note change in braces)

I tried to select the key with this regex:
\{\!\! \$arr\[.*.] !!} which works but how do I now replace it?

EDIT:

I only want to select array key which is variable so my regex doesn’t work – it selects whole line.

How to&Answers:

In PhpStorm, open the replace dialogue and make sure you’ve checked the Regex checkbox.

For your find, you can use:

(\{!!\s*$\w+)\[('[\w\.]+')\](\s*!!\})

This captures the 3 parts you want to keep. You then replace the brackets and use $1, $2 and $3 to insert your original content around the new brackets.

$1($2)$3

Screenshot of how to do this:

enter image description here

Answer:

You can search like this with phpstorm:

  • (\{\!\!.+\$.+)(\[) replace by $1(
  • (])(.*\!\!}$) replace by )$2

Don’t forget to check the box regex in search toolbar.