Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Routing regex problem

I'm trying to match something like:

mydomain.com/something

mydomain.com/something/2

Both should work.

This is my route:

$router->add("/{board:[a-zA-Z_]+}/{page:[0-9]?}", [ 'controller' => 'board', 'action' => 'show'] )->setName('show-board');

This however requires the trailing slash even without the page specified. Is there a way to need the slash ONLY with the page?



2.6k
Accepted
answer
$router->add("/{board:[a-zA-Z_]+}/?{page:[0-9]*}", [ 'controller' => 'board', 'action' => 'show'] )->setName('show-board');

You probably need one or more numbers for the page param, so i replaced the question mark (zero or one occurrence) with the asterisk (zero or multiple occurrences)



3.3k
edited Mar '14

Hey. That works for the routing part. However $url->get(); builds incorrect links with that route. ( domain.com/board/?2 ). Is there something I could do to make to $url->get(); to not put that question mark to the URL?

This is the function that builds the wrong link:

{{ url.get(['for': 'show-board', 'board': title, 'page': page.before]) }}

You could add two routes:

$router->add("/{board:[a-zA-Z_]+}", [ 'controller' => 'board', 'action' => 'show'] )->setName('show-board');
$router->add("/{board:[a-zA-Z_]+}/{page:[0-9]+}", [ 'controller' => 'board', 'action' => 'show'] )->setName('show-board-pagination');


3.3k

Yep, that's what I've been doing, was just wondering if there was a better/shorter way. Thanks. :P