if(!empty($_SERVER['REQUEST_URI'])){ return trim($_SERVER['REQUEST_URI'],'/'); } //возвращает uri foreach ($routes as $controller => $method) { if (preg_match("~$controller~",$uri)){ $internalRoute = preg_replace("~$controller~", $method, $uri); $segments = explode('/',$internalRoute); echo $internalRoute; print_r($segments); echo $uri; } } 

Here is an array of routes

  'product/([0-9]+)' => 'product/view/$1', 'catalog' => 'catalog/index', '' =>'mainPage/index', 'test' =>'test/view' 

When I type test.com/index into the address bar, I get

 mainPage/indextmainPage/indexemainPage/indexsmainPage/indextmainPage/index //$internalRoute Array ( [0] => mainPage [1] => indextmainPage [2] => indexemainPage [3] => indexsmainPage [4] => indextmainPage [5] => index ) test/viewArray ( [0] => test [1] => view ) //$segments index //$uri 

How to fix that he gave me a string corresponding route? As in the pattern of the routes below.

 'product/([0-9]+)' => 'product/view/$1', 'catalog' => 'catalog/index', '' =>'mainPage/index', 'test' =>'test/view' 
  • '' =>'mainPage/index', corresponds to anything, if I'm not mistaken. Try to specify the line boundary in the form '^$' =>'mainPage/index', - Visman
  • @Visman Pointed out, but this did not fix anything . The problem is not this - ThreegunD
  • You would add $uri output before the loop and display it in the question. - Visman
  • @Visman is ready, everything is fine with uri. - ThreegunD

1 answer 1

The preg_replace function will replace the found pattern as many times as it will meet, unless you specify a limit in the arguments.

I propose this version of the code. Also without specifying limits, but indicating the beginning of the line:

 <?php $routes = array( '^product/([0-9]+)' => 'product/view/$1', '^catalog' => 'catalog/index', '^$' =>'mainPage/index', '^index' =>'mainPage/index', '^test' =>'test/view', ); $uri = 'product/1354'; foreach ($routes as $controller => $method) { if (preg_match("~$controller~",$uri)){ $internalRoute = preg_replace("~$controller~", $method, $uri); $segments = explode('/',$internalRoute); echo "<pre>\n"; echo 'uri="' . $uri . "\"\n\n"; echo $internalRoute . "\n"; print_r($segments); echo "</pre>\n"; } } 

And the results:

 uri="product/1354" product/view/1354 Array ( [0] => product [1] => view [2] => 1354 ) --- uri="" mainPage/index Array ( [0] => mainPage [1] => index ) --- uri="index" mainPage/index Array ( [0] => mainPage [1] => index ) 
  • everything would be fine, but if you point out such an uri "test.com/test34/1354" for example, the router also works and displays this uri = "test34 / 1354" test / view34 / 1354 Array ([0] => test [1] => view34 [2] => 1354) - ThreegunD
  • add "$" to the ends of the router, as I understand it? - ThreegunD
  • @ThreegunD, yes, so that there is full compliance with the query string, and not its beginning. - Visman
  • It works fine now :) - ThreegunD