Zend Basic Tutorial
Zend Forms
Zend Database
Zend Advanced
A Regex Route allows you to define highly customized and flexible URL patterns using regular expressions. This is helpful when standard route types like Literal or Segment are too limited.
|
Use Case |
Regex Pattern |
Acceptable URL(s) |
|---|---|---|
|
Username profile |
/user/(?<username>[a-zA-Z0-9_-]+) |
/user/john_doe, /user/John123 |
|
Product by code |
/product/(?<code>[A-Z]{3}-[0-9]{4}) |
/product/ABC-1234, /product/XYZ-0001 |
|
Archive by date |
/archive/(?<year>[0-9]{4})/(?<month>[0-9]{2}) |
/archive/2023/07, /archive/2025/12 |
|
Slug with dots |
/docs/(?<slug>[a-z0-9\.-]+) |
/docs/html.basics, /docs/css.advanced |
use Application\Controller\MainController;
'router' => [
'routes' => [
'archive' => [
'type' => \Laminas\Router\Http\Regex::class,
'options' => [
'regex' => '/archive/(?<year>[0-9]{4})/(?<month>[0-9]{2})',
'defaults' => [
'controller' => MainController::class,
'action' => 'show',
],
'spec' => '/archive/%year%/%month%',
],
],
],
],
namespace Application\Controller;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\View\Model\ViewModel;
class MainController extends AbstractActionController
{
public function showAction()
{
$year = $this->params()->fromRoute('year');
$month = $this->params()->fromRoute('month');
return new ViewModel([
'year' => $year,
'month' => $month,
]);
}
}
<h2>Archive Page</h2> <p>Year: <?= $this->escapeHtml($year) ?></p> <p>Month: <?= $this->escapeHtml($month) ?></p>
|
URL |
Matched Action |
Output |
|---|---|---|
|
/archive/2024/07 |
showAction() |
Year: 2024 Month: 07 |
|
/archive/1999/12 |
showAction() |
Year: 1999 Month: 12 |