使用 URI 值映射路由器占位符

Map the router placeholder with the URI values

我不知道怎么解释,所以请放轻松。

路由器持有uri变量key

$router = 'movie/english/{slug}/edit/(id}/{title}';

浏览器地址栏中的URI

$uri = 'movie/english/scorpion/edit/125/E01E05';

如何编写将路由器占位符变量映射到 URI 匹配值的代码。例如

array(
    'slug' => 'scorpion',
    'id' => '125',
    'title' => 'E01E05'
);

如果你明白,能否将我重定向到正确的资源。

如果我理解你的要求是正确的,可以通过 str_replace:

通过详细信息数组将 $router 转换为 $uri
$router = 'movie/english/{slug}/edit/{id}/{title}';

$details = array(
    'slug' => 'scorpion',
    'id' => '125',
    'title' => 'E01E05'
);

$uri = str_replace(array('{slug}','{id}','{title}'), $details, $router);

echo $uri;
// movie/english/scorpion/edit/125/E01E05

您可以为此编写自定义解决方案,但每次您需要更多内容时都会显示 wheel,这就是为什么我的建议使用最佳实践:

composer require symfony/routing

<?php

require './vendor/autoload.php';

use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

$route = new Route(
    '/movie/english/{slug}/edit/{id}/{title}',
    array('controller' => 'MyController')
);
$routes = new RouteCollection();
$routes->add('route_name', $route);

$context = new RequestContext();
$matcher = new UrlMatcher($routes, $context);
$parameters = $matcher->match('/movie/english/scorpion/edit/125/E01E05');

var_dump($parameters);

将打印:

array (size=5)
  'controller' => string 'MyController' (length=12)
  'slug' => string 'scorpion' (length=8)
  'id' => string '125' (length=3)
  'title' => string 'E01E05' (length=6)
  '_route' => string 'route_name' (length=10)

我坚信这是最好的解决方案,希望对您有所帮助。