-2

I want to run a regex search from inside PhpStorm (could be any file manager though, Double/Total Commander handles regex searches just as well) to match php variables that are inside single quotes and therefore string interpolation won't work on them e.g. '$var'.

The content of the files would be something like this:

$var = 'Hello world!';

echo 'Lorem ipsum $var dolor sit amet'; // Match this.
echo "Lorem ipsum 'dolor sit amet $var consectetur' adipiscing elit"; // But not this.
echo "Lorem ipsum 'dolor sit amet \$var consectetur' adipiscing elit"; // Or this.

I want the regex search to match the first statement, but not the second or third.

I've tried '[\w ]+\$[\w]+[\w ]+' but that doesn't work because it matches all statements regardless of the double quotes or escaped dollar sign. (regex101).

This is just a regular regex search that I want to run on my repo to find buggy code.

What regex could I use for this?

(I don't need to get any text in between quotes, just php variables in between single quotes that aren't escaped.)

Ethan
  • 4,295
  • 4
  • 25
  • 44

1 Answers1

1

What you need is negative lookaround. In particular, negative lookahead, because in PHP you are not allowed to use no-fixed-length lookbehind:

'[\w ]+\$[\w]+[\w ]+'(?![\w$ ']*")

(?![\w$ ']*") means that the string that you want to match must not be followed by a ", with any number of character (the ones that you want to allow in a string) in the middle.

See also: http://www.regular-expressions.info/lookaround.html

logi-kal
  • 7,107
  • 6
  • 31
  • 43