Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can I use regex without a variable? Can I use flags? #210

Open
adjenks opened this issue Feb 25, 2020 · 3 comments
Open

Can I use regex without a variable? Can I use flags? #210

adjenks opened this issue Feb 25, 2020 · 3 comments

Comments

@adjenks
Copy link

adjenks commented Feb 25, 2020

Regex with no variable:

    $r->addRoute('GET', '/{user|person}', 'get_user_handler');

Case insensitive flag:

    $r->addRoute('GET', '/{/user/i}', 'get_user_handler');

I tried both, they did not work. Am I doing it wrong?

@adjenks
Copy link
Author

adjenks commented Feb 25, 2020

My current workaround for both is to make a variable with a name I won't collide with, and use a 'mode modifier', eg.(?i), which I was unaware existed until this use case.

Example:

   $r->addRoute('GET', '/{junk_variable:(?i)user}', 'get_user_handler');

@adjenks
Copy link
Author

adjenks commented Feb 25, 2020

multiple route sections where you want to use regex force you to assign multiple junk variables though.

@weroro-sk
Copy link

multiple route sections where you want to use regex force you to assign multiple junk variables though.

I didn't find an official solution, so if anyone needs it, here's a hacky option.

I solve it like this:

$r->addRoute('GET', '/{_-_:(?i)user}', 'get_user_handler');

// or in my case (uri wildcard)
$r->addRoute('GET', '/[{_-_:.*}]', 'get_user_handler');
case FastRoute\Dispatcher::FOUND:
  $handler = $routeInfo[1];
  $vars = $routeInfo[2];

  if (array_key_exists('_-_', $vars)) {
      unset($vars['_-_']);
  }

  // ... call $handler with $vars
  break;

btw: variable name in regular expression can contain - character and that is not a valid character for variables.

$r->addRoute('GET', '/[{_-_:.*}]', 'get_user_handler');

This is valid, but I cannot create an argument variable named $_-_. So it can be used as a name, but it cannot be used as a variable, so we can remove it from the $vars array.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants