We are switching from array() to [] in our php code. And when I start to do code refactoring I found that almost all arrays are specified with array() and not with []. How can I substitute it by vim?


// アクセスログを取る
$this->set('log_access', array(
    'target' => 'topic',
    'id'     => $id

I want to change to:

// アクセスログを取る
$this->set('log_access', [
    'target' => 'topic',
    'id'     => $id


$opts    = array('http' => array('header' => 'User-Agent: iPhone-preview'));

I want to change to:

$opts    = ['http' => ['header' => 'User-Agent: iPhone-preview']];

Certainly looks like a case for a macro

  • /array<CR> to jump to the first array
  • qq to record the macro into register q
  • de to delete the word array
  • ma to save the cursor position on the first bracket at mark a
  • %r] to jump to the matching bracket, replace it by another bracket
  • `ar[ to jump back to position a and replace that bracket
  • q to end recording of the macro

After that, it's just repeatedly pressing n to jump to the next match and @q to play the macro. You could make the search part of the macro and just execute until it stops, but I thought you might prefer to visually check each substition... you choose :)

| improve this answer | |
  • 1
    Interesting, +1. I was thinking using RE but discovered that's not possible: stackoverflow.com/questions/5139300/… – Rmano Feb 19 '16 at 9:42
  • +1 also. Just a minor possible improvement, if Vim is recent enough to support the gn object, you could replace de with dgn to delete the next occurrence of the last searched pattern. You could still check each substitution, but you wouldn't have to hit n before replaying the macro with @q. – saginaw Feb 19 '16 at 10:05
  • 3
    Interesting suggestion, thanks. I'll just leave it like that anyways, because using n + @q has the advantage of possibly highlighting the match, which might make the whole process go down easier. Just so many possibilities... – PhilippFrank Feb 19 '16 at 10:08
  • 1
    Yes you're right, gn is probably not really useful here, because the searched pattern is well-defined and not a regex whose length may vary. Plus I didn't think you could simply add the n motion inside the macro, your approach adds the benefit of really seeing what's going on at each step of the process. – saginaw Feb 19 '16 at 10:25
  • 1
    The other good thing of adding the search to the macro could be the possibility to apply it to the whole buffer with :% normal @a... yes, a lot of possibilities. – Rmano Feb 19 '16 at 10:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.