DEV Community

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

Posted on

10 2

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}',

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

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().

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay