From 398a5bb41a78087c7740efcecaf282346960a281 Mon Sep 17 00:00:00 2001 From: Taylor Otwell Date: Wed, 13 Jul 2011 17:28:42 -0500 Subject: [PATCH] added support for optional route parameters. --- system/router.php | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/system/router.php b/system/router.php index 86715ece..dc9a870c 100644 --- a/system/router.php +++ b/system/router.php @@ -41,7 +41,7 @@ public static function route($method, $uri) { foreach (explode(', ', $keys) as $key) { - if (preg_match('#^'.$key = static::translate_wildcards($key).'$#', $uri)) + if (preg_match('#^'.static::translate_wildcards($key).'$#', $uri)) { return Request::$route = new Route($keys, $callback, static::parameters($uri, $key)); } @@ -77,14 +77,25 @@ private static function load_from_directory($uri) } /** - * Translate route URI wildcards to regular expressions. + * Translate route URI wildcards into actual regular expressions. * * @param string $key * @return string */ private static function translate_wildcards($key) { - return str_replace(':num', '[0-9]+', str_replace(':any', '[a-zA-Z0-9\-_]+', $key)); + $replacements = 0; + + // For optional parameters, first translate the wildcards to their regex equivalent, sans the ")?" ending. + $key = str_replace(array('/(:num?)', '/(:any?)'), array('(?:/([0-9]+)', '(?:/([a-zA-Z0-9\-_]+)'), $key, $replacements); + + // Now, to properly close the regular expression, we need to append a ")?" for each optional segment in the route. + if ($replacements > 0) + { + $key .= implode('', array_fill(0, $replacements, ')?')); + } + + return str_replace(array(':num', ':any'), array('[0-9]+', '[a-zA-Z0-9\-_]+'), $key); } /**