简体   繁体   中英

Matching a url to a route with Regex

I have a route like so (YAML):

hello_route:
    path: /hello
    controller: HelloController
    action: helloAction

this works fine and calls the correct controller and action, but I am having a hard time matching wildcards. For instance, if I wanted to add:

hello_route:
   path: /hello/{name}
   controller: HelloController
   action: helloAction

I tried using Regex but when you type /hello/bob in the browser, no matter what I did with regex it kept saying there was no route. How can I use regex for the URI /hello/bob to still match /hello/{name} ? As of right now it literally looks for the /{name} which obviously != /bob

I am using this function so far because I thought that replacing the {name} with a * would make the browser treat it as a wild card. But that doesn't work.

/**
 * Compiles routes
 *
 * @param  array $routes
 * @return string
 */
public function compileRoutes(array $routes)
{
    foreach($routes as $key => $val)
    {
        if($val['path'])
        {
            preg_match_all('/\{(\w+?)}/', $val['path'], $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);

            foreach ($matches as $match)
            {
                if(isset($matches[0]) && isset($matches[1]))
                {
                    $matches[0] = '*';
                    $val['path'] = $matches[0];
                    $this->params[] = $matches[1]; 
                }
            }
        }
    }

    $this->routes = $routes;
}

here is the return for @Tuga

/
/test
/hello/{name} <- not being replaced

I don't know what you want, but the syntax of this regex is wrong

\{(\w+?)}

It needs to be, either this :

\{(\w+?)\}

or this:

(\w+?)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM