PhpStorm 2016.3 Help

Finding and Replacing Text in File Using Regular Expressions

On this page:

Example code

Consider the following XML code fragment:

<new product="ij" category="105" title="Multiline search and replace in the current file" /> <new product="ij" category="105" title="Improved search and replace in the current file" /> <new product="ij" category="105" title="Regexp shows replacement preview" /> ...

Finding and replacing a string using regular expression

Suppose you want to replace an attribute within an element (title) with an expanded tag <title></title>, which contains some arbitrary string in double-quotes within.

This is how it's done.

  1. With the XML file in question opened in the editor, press Ctrl+R. The Replace pane appears on top of the editor.
  2. Since you want to replace all the title attributes, regardless of the actual strings contained therein, use regular expressions. Make sure that the check box Regex is selected. Thus everything you type in the Search and Replace fields will be perceived as the regular expressions.
  3. In the Search field, start typing regular expression that describes all title attributes. Note that though the regular expression \stitle=".*?"\s*[/>]* matches contents of the title attribute, it is recommended to capture the groups for referencing them in the Replace field:
    \stitle="(.*)?"\s*(/>*)

    Note that for the regular expressions replacement preview is shown at the tooltip:

    /help/img/idea/2016.3/replaceText.png
  4. Then, in the Replace field, type the following regular expression:
    $2<title>$1</title>
  5. Click Replace, or Replace All.

As you see, the second capture group (/>) is moved ahead to close the <new> element, while the first capture group <, which matches any string in double quotes, is moved to the element <title>.

Changing case of the characters

Suppose now that you want to change characters os the search strings. Again make sure that Regex check box is selected.

In the Search field, type the search expression:

\stitle="(.*)?"\s*(/>*)

Next, fill in the Replace field with the following expression:

\U$1

The found occurrences are replaced with the upper-case characters:

/help/img/idea/2016.3/replaceText1.png

Next, let's make the strings all lower-case. To replace occurrences with the lower-case characters, type the following replacement string:

\L$1

Then the suggested replacement will be:

/help/img/idea/2016.3/replaceText2.png

And finally, if you want change the case of the first letter only, type the following replacement string:

\l$1

PhpStorm suggests the following replacement:

/help/img/idea/2016.3/replaceText3.png

See Also

Last modified: 23 March 2017