Search code examples
phpregexphpstorm

RegEx expression to replace delimiters separating words


In PhpStorm, I'd like to replace a PHP array variable with a function call in the following way:

$trad['newsletter']['title']['something'];
$trad['newsletter']['placeholder'];
$trad['buttons']['send']['text']['small'];

The result would be:

lang('newsletter.title.something');
lang('newsletter.placeholder');
lang('buttons.send.text.small');

I have tried with the expression

\$trad\s?\[(.+('\]\[').+)\]

but only captures the last occurrence of ']['


Solution

  • First step for three keyed expressions: \$trad\s?\['([\w\-]+)']\['([\w\-]+)']\['([\w\-]+)'\]([^\[]) replace with lang('$1.$2.$3)$4. Second step for two keyed expressions: \$trad\s?\['([\w\-]+)']\['([\w\-]+)'\]([^\[]) replaced with lang('$1.$2')$3. I optimized the code to avoid more than 3 keys.