3v4l.org

run code in 300+ PHP versions simultaneously
<?php // Change me! $userSpecifiedPath = '/'; // works, HomepageController // $userSpecifiedPath = '/asdf'; // route doesn't exist, 404Controller //$userSpecifiedPath = '/deep/nested/controller'; // // Don't edit below =============================================== // ================================================================ // Simple config example // ================================================================ $routerConfig = <<<CONFIG [/] Controller = "HomepageController" [/deep*] Controller = "DeepController" [404] Controller = "404Controller" CONFIG; // ================================================================ // Simple router example // ================================================================ class Router { private $routes; public function __construct($routes) { $this->routes = $routes; } public function getRouteFromPath($path) { if(array_key_exists($path, $this->routes) === true) { return $this->routes[$path]; } $hierarchical = $this->getHierarchicalRouteFromPath($path); if(!empty($hierarchical)) { return $hierarchical; } elseif(array_key_exists('404', $this->routes) === true) { return $this->routes['404']; } throw new Exception('No controllers found.'); } public function getAllHierarchicalRoutes() { $routes = array(); foreach($this->routes as $key => $route) { if(strpos($key, '*') === strlen($key) - 1) { $routes[$key] = $route; } } return $routes; } public function getHierarchicalRouteFromPath($path) { foreach($this->routes as $key => $route) { if(strpos($key, '*') === strlen($key) - 1) { if(strpos($path, rtrim($key, '*')) === 0) { return $route; } } } } } // ================================================================ // Sample output // ================================================================ $routes = parse_ini_string($routerConfig, true); $Router = new Router($routes); $selectedRoute = $Router->getRouteFromPath($userSpecifiedPath); echo 'Using controller: ' . $selectedRoute['Controller'];

preferences:
37.23 ms | 402 KiB | 5 Q