Zend Regex Route

What is a Regex Route?

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 Examples:

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


Full Example

Step 1: Route Configuration (module/Application/config/module.config.php)

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%',
      ],
    ],
  ],
],

Step 2: Controller Setup (module\Application\src\Controller\MainController.php)

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,
    ]);
  }
}

Step 3: View File (view/application/main/show.phtml)

<h2>Archive Page</h2>
<p>Year: <?= $this->escapeHtml($year) ?></p>
<p>Month: <?= $this->escapeHtml($month) ?></p>

Access in Browser

URL

Matched Action

Output

/archive/2024/07

showAction()

Year: 2024

Month: 07

/archive/1999/12

showAction()

Year: 1999

Month: 12


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.