2

I don't how to explain this so please be easy on me.

The router holds the uri variable key

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

The URI in the browser address bar

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

How can I write the code that will map the router placeholder variable with the URI matching value. E.g.

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

Please if you understand can you redirect me to the correct resource.

cn007b
  • 16,596
  • 7
  • 59
  • 74
Red Virus
  • 1,633
  • 3
  • 25
  • 34

2 Answers2

1

You can write custom solution for this, but you will reveal wheel every time when you will need something more, that's why my advice use the best practice:

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);

will print:

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)

I truly believe that it's the best solution, hope it'll help you.

cn007b
  • 16,596
  • 7
  • 59
  • 74
0

If I'm understanding what you're asking correctly, transforming $router to $uri via the array of details can be accomplished with str_replace:

$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
danjam
  • 1,064
  • 9
  • 13