1

I have a large PHP codebase with many instances of this pattern:

$result = $expression? $expression: $alternate;

Which I want to replace with:

$result = $expression ?: $alternate;

Here $expression can be anything like $this->system->cache('1234'). It will usually start with $, and usually not have any spaces in it. Those few that don't start with $ or have spaces, I can review manually.

I can get a RegEx to match the above, allowing for optional whitespace:

(\$[^? ]+) *\? *(\$[^: ]+) *:

But this won't guarantee that group 1 and group 2 are the same.

Is there a way to match these patterns?

Yimin Rong
  • 1,890
  • 4
  • 31
  • 48

1 Answers1

1

You can use backreference \1 -- reference to the first matching group, i.e.:

(\$[^? ]+) *\? *\1 *:
Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125