DEV Community

Cover image for How to flip array keys and values in the code editor?
Insolita
Insolita

Posted on

How to flip array keys and values in the code editor?

Easy, with regex search!

  • Press Ctrl+R for show replace bar
  • Enable regex mode (button looks like .* near search field)
  • Use regex in search field: '(.+)'\s=>\s'(.+)',
  • Use expression for replace: '$2' => '$1',

You can see a tooltip with a value that will be after replace

Alt Text

It is possible even you have different quotes and spaces between arrow

Use regex
(?:'|")(.+)(?:'|")\s{0,}=>\s{0,}(?:'|")(.+)(?:'|"),

And the same replace expression '$2' => '$1',

Alt Text

Named capture groups also available:

Use regex
(?:'|")(?<src>.+)(?:'|")\s{0,}=>\s{0,}(?:'|")(?<tgt>.+)(?:'|"),

And the same replace expression '${tgt}' => '${src}',

Top comments (2)

Collapse
 
voyeg3r profile image
Sérgio Araújo • Edited

As a test I have tried on vim

/\v^('\w+')( .. )('\d+'),
:%s//\3\2\1,
Enter fullscreen mode Exit fullscreen mode

OBS: I have used the caret as if the pattern started at the begining of line but we can also cosider the space optional

/\v^(\s+)?('\w+')( .. )('\d+'),
:%s//\1\4\3\2
Enter fullscreen mode Exit fullscreen mode

Another tip: Using neovim we have the "inccommand" that allow us to match our regex icrementally. Then we can refer to our search simply by using //

Collapse
 
rulatir profile image
rulatir

"Easy" and "with regex search" are mutually exclusive concepts, and I am saying this as a regex enthusiast who routinely fixes other people's code by replacing naïve matching like strpos() with preg_match().