⊗ppPmSDRNP 445 of 447 menu

Routing with Named Parameters in PHP

Let's consider one of the regular expressions that process the URL:

<?php if (preg_match('#^/page/([a-z0-9_-]+)$#', $url, $params)) { $page = include 'view/page/show.php'; } ?>

In this case, our parameter ends up in a capture group. Then we extract the parameter value from the capture group by its number:

<?php $slug = $params[1]; ?>

This is actually not very elegant, especially if there are several parameters. A better idea would be to have parameters with names instead of numbers. To do this, we use named capture groups in our regex:

<?php if (preg_match('#^/page/(?<slug>[a-z0-9_-]+)$#', $url, $params)) { $page = include 'view/page/show.php'; } ?>

In this case, we can get the value of the parameter by its name:

<?php $slug = $params['slug']; ?>

Convert the parameters in your engine's routes to named ones.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline