Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex change "array()" to "[]" in Sublime 3

Yet another RegEx question. I have many PHP files to change from array('foo', 'bar') to new style ['foo', 'bar']

So far I came up with this:

array\(([^\(]*?)\)

But it doesn't pick up multi-line definitions. I've tried something like this, but it's even worse, since it picks up wrong closing brackets:

(?s)array\(([^\(].*?)\)

For example, some data that needs to get replaced:

$foobar = $this->foobar('foo_bar', array(
    'foo'   =>  array('foobar' => array('barfoo')),
    'bar' => array(
        'bar' => 'foobar',
        'foo' => 'barfoo',
)));

So the above example would look like this:

$foobar = $this->foobar('foo_bar', [
    'foo' => ['foobar' => ['barfoo']],
    'bar' => [ 
        'bar' => 'foobar',
        'foo' => 'barfoo',
 ]]);

Anyone? Thanks!

like image 306
simon Avatar asked Dec 29 '25 13:12

simon


1 Answers

In Sublime Text, you can use multiple passes with 

\barray(\(((?>[^()]++|(?1))*)\))

and replace with [$2].

The pattern matches:

  • \b - leading word boundary
  • array - a literal character sequence array
  • (\(((?>[^()]++|(?1))*)\)) - Group 1 matching nested, paired parentheses and capturing the contents between paired parentheses into Group 2 (that is why you need to backreference Group 2 with $2 in the replacement).
like image 92
Wiktor Stribiżew Avatar answered Dec 31 '25 05:12

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!