How Use A Little Regex In PHPStorm’s Find
Frank Wallen • July 13, 2018development phpstorm
I had a recent task to upgrade jQuery in a very large, mature application. It’s been chugging along doing its job for more than a decade. Many developers have come through and added their work, so its had quite a bit of growth, as you can imagine. Eventually, any online application will need to get and stay current when it comes to security. Not having that on your radar, at minimum, if not scheduled, is a fool’s game these days. That said, let’s move on to what this article really is about: Using regex in PHPStorm’s Find and Find/Replace features.
Once I had installed the latest version of jQuery I needed to begin the process of updating, adding, or correcting usage of the library. Keep in mind, as this is a mature application, page rendering is done many various ways, old-style flat file PHP and newer MVC-style (pre-Laravel and now leveraging Laravel); so there were many layouts and pages doing it their own way. Searching for specific issues, such as
.attr('select') isn't too difficult but it was easier, by far, to locate using some regex during the search.
If you open
Find > Find In Path you will see there are several options at the top of the dialog box for casing, words, file masking, and regex. Select that option and you can begin using regex in the text input. To start, I did the following:
This regex expression is not complicated at all (Regex is an incredibly powerful and complex search pattern, https://en.wikipedia.org/wiki/Regular_expression). The
backslashes (escapes) are required since $, (, and . are all syntax in regex. This tells the search engine that those characters are actually characters to be located. The
.* basically means ‘include everything.’ In this case what we’re telling the search engine to find is anything that looks like
$(foo) , but anywhere, so if there’s a
$('input').val(), no matter what follows or precedes, that line will be presented in the results window. I had to be more exact in some cases due to migrating jQuery versions, so I did use
.*\$\(.*\)\.attr\('select'\). As you might guess, I was looking for implementations like
$('#input').attr('select'). Remember that
( are syntax in the regex expression, so they needed to be escaped. Brackets
 are also, so if you wanted to look for specific attributes in a selector like
$('input[name=first]') you would have to escape the characters like this:
PHPStorm’s Find/Replace feature also takes regex for searching. With a clever regex expression, replacing multiple instances of a string across files can be a lot less painful. You can also include the ‘Match case’ option in the find window, so you don’t need to do the usual regex methods if you may have case variations.
Regex can, at first, intimidate, but it is an extremely useful tool to learn, especially in the programming language you work with every day.