Use of Capture Groups in Regular Expressions for Routing

PHP offers very powerful tools that you may use to create routing for your MVC framework. Using regular expressions instead variable strings in URL routing may save you from writing many lines of code.

Let’s take a look at the preg_match() function. As we know, the function takes the sting and looks if it matches to the regular expression.

preg_match($reg_exp, $string)

If the string matches, the function returns 1. If not, it returns 0. But there is also an optional third parameter to this function, which will collect the results of the match in an array:

<?php 
preg_match("/[0-9]+/", "132", $match);
var_dump($match);

// Result: array(1) { [0]=> string(3) "132" }

Now we can use regular expression Capture Groups denoted as parentheses to catch more than one result into that array:

<?php 
preg_match("/a([0-9]+)b/", "a132b", $match);
var_dump($match);

// Result: array(2) { [0]=> string(5) "a132b" [1]=> string(3) "132" }

We also can use two groups like this:

<?php
preg_match("/([a-zA-Z]+) (\d+)/", "Apr 2017", $match);

// Result: array(3) { 
  [0]=> string(8) "Apr 2017" 
  [1]=> string(3) "Apr" 
  [2]=> string(4) "2017" }

We even can give names to the capture groups, that will be used in the $match array along with the numbers:

<?php
preg_match("/(?[a-zA-Z]+) (?\d+)/", "Apr 2017", $match);

// Result: array(5) { 
  [0]=> string(8) "Apr 2017" 
  ["month"]=> string(3) "Apr" 
  [1]=> string(3) "Apr" 
  ["year"]=> string(4) "2017" 
  [2]=> string(4) "2017" }

To get an array with the strings only, use a foreach loop:

<?php
preg_match("/(?[a-zA-Z]+) (?\d+)/", "Apr 2017", $matches);
$results=[];
foreach ($matches as $key => $match ) {
    if (is_string($key)) {
        $results[$key] = $match;
    }
}

// Result: array(2) { 
  ["month"]=> string(3) "Apr" 
  ["year"]=> string(4) "2017" } 

Now it is much easier to match URL to controllers in a MVC framework.