We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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?



3.2k
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)



5.6k
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');


5.6k

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