xp-framework / compiler

Compiles future PHP to today's PHP.
19 stars 0 forks source link

Regex syntax exploration #130

Closed thekid closed 2 years ago

thekid commented 2 years ago

Idea 1: Tilde operator

Input:

if ($greeting ~ '/^H[ea]llo/') {
  // Matches!
}

if ($matches= $greeting ~ '/^H[ea]llo/') {
  // Work with $matches
}

Rewritten to:

if (preg_match($greeting, '/^H[ea]llo/')) {
  // Matches!
}

if (preg_match($greeting, '/^H[ea]llo/', $matches)) {
  // Work with $matches
}

Idea 2: Regex literal

Input:

if (/^H[ea]llo/->matches($greeting)) {
  // Matches!
}

Rewritten to:

if (Pattern::compile('/^H[ea]llo/')->matches($greeting)) {
  // Matches!
}

Idea 3: Tagged template literal

Inspired by JavaScript template literals:

Input:

if (r`/^H[ea]llo/`($greeting)) {
  // Matches!
}

Rewritten to:

if (preg_match('/^H[ea]llo/', $greeting)) {
  // Matches!
}

Prior art

thekid commented 2 years ago

First idea implemented as plugin -> https://github.com/xp-lang/php-pattern-operator