创建可选路由参数PHP的解决方案

创建可选路由参数PHP的解决方案,php,regex,routes,Php,Regex,Routes,我为我的PHP应用程序创建了Route类。一切正常,这是我的功能分派: public function dispatch() { //some code... $search = array(); $regex = preg_replace_callback( '#{([\w]+)?(:([^/\(\)]*))?}#', function($m) use (&$search) { $searc

我为我的PHP应用程序创建了Route类。一切正常,这是我的功能分派:

public function dispatch()
{
    //some code...
    $search = array();
    $regex = preg_replace_callback(
          '#{([\w]+)?(:([^/\(\)]*))?}#',
           function($m) use (&$search) {
               $search[$m[1]] = null;
               if (isset($m[3])) {
                   return '(?P<'.$m[1].'>'.$m[3].')';
               }
               return '(?P<'.$m[1].'>[^/\?]+)';
           },
           str_replace(array(')','/+'), array(')?','(/?|/.*?)'), $pattern)
    );
    $regex .= ($last === '/') ? '?' : '/?';
    $regex = '#^'.$regex.'$#i';
    if (preg_match($regex, $url, $matches)) {
        // some code...
    }
    // some code...
}
可选路线:

$router->add('/user(/{id})', function($id) {
    echo 'User ID: ' . $id;
});
它正在工作,但我想将语法从“/user(/{id})”更改为“/user/{id?}”,我该怎么做?我想可能会把regex“#{([\w]+)?(:([^/()]*)?}”改成什么,但我不能。有人帮我吗?

您可以使用以下任一项来匹配:
\/\{(\w+)(\?)?\}

这将匹配任何
/{param}
/{param?}
。您将检查是否捕获了“?”以检查它是否是可选的


该表达式将匹配只包含字母的参数,您可以通过这样的操作轻松地将其扩展为任何字符:
\/\{([a-zA-Z0-9\-\\\\\\\\)(\?)?\}

我认为regex应该类似于| user/d*/?;但不精通regexp,所以不能确定。
$router->add('/user(/{id})', function($id) {
    echo 'User ID: ' . $id;
});