ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Simple Route Matching

PHP

Goal -- WPM

Ready
Exercise Algorithm Area
1<?php
2
3/**
4* Matches a URL path against a list of predefined routes.
5*
6* @param string $path The URL path to match.
7* @param array $routes An array of route definitions, where each key is a path pattern and the value is a route name.
8* @return string|null The name of the matched route, or null if no match is found.
9*/
10function matchRoute(string $path, array $routes): ?string
11{
12// Normalize the path to ensure consistency.
13$normalizedPath = '/' . trim($path, '/');
14
15// Iterate through each defined route.
16foreach ($routes as $pattern => $routeName) {
17// Handle exact matches first.
18if ($pattern === $normalizedPath) {
19return $routeName;
20}
21
22// Handle wildcard matches (e.g., '/users/*').
23if (str_ends_with($pattern, '/*')) {
24$basePattern = rtrim($pattern, '/*');
25if ($basePattern === '' || str_starts_with($normalizedPath, $basePattern . '/')) {
26return $routeName;
27}
28}
29}
30
31// If no route matches, return null.
32return null;
33}
34
35?>
Algorithm description viewbox

Simple Route Matching

Algorithm description:

This function simulates a basic part of MVC routing by matching a given URL path against a predefined set of route patterns. It iterates through the routes, checking for exact matches or wildcard matches to determine which controller action should be invoked. This is fundamental for directing incoming web requests to the correct application logic.

Algorithm explanation:

The `matchRoute` function takes a URL path and an associative array of route patterns to route names. It first normalizes the input path by ensuring it starts and ends with a single slash. Then, it iterates through the provided routes. For each route, it checks if the normalized path exactly matches the pattern. If not, it checks if the pattern ends with '/*' to identify a wildcard route. If it's a wildcard, it extracts the base pattern and checks if the normalized path starts with that base pattern followed by a slash. If a match is found, the corresponding route name is returned. If the loop completes without finding a match, null is returned. This approach has a time complexity of O(N*M) in the worst case, where N is the number of routes and M is the average length of the path and pattern strings, due to string comparisons. Space complexity is O(1) as it only uses a few variables.

Pseudocode:

function matchRoute(path, routes):
  normalize path
  for each pattern, routeName in routes:
    if path equals pattern:
      return routeName
    if pattern ends with '/*':
      basePattern = pattern without '/*'
      if path starts with basePattern + '/':
        return routeName
  return null