我现有的代码:
// Define the routes
$routes = [
'/programs',
'/programs/{}',
'/programs/{}/{}',
'/programs/{}/test/{}'
];
// Example URL
$url = '/programs/part_1/test/part_2';
/*
* Split the URL at /
* Remove the first and last value from the returned array
*/
$parts = array_values( array_filter( preg_split( "/\//", $url ) ) );
// Define valid routes array
$valid_routes = $routes;
// Loop over the defined routes
foreach($routes as $route){
// Split the route into parts, like we do with the url
$route_parts = array_values( array_filter( preg_split( "/\//", $route ) ) );
/*
* If the route parts is more than the parts of the url
* then continue to the next value in the routes array
*/
if( sizeof( $route_parts ) != sizeof( $parts ) ){
// Remove the route from the valid routes array
$valid_routes = array_values( array_diff( $valid_routes, [$route] ) );
}
// Loop over the route parts
for( $i=0; $i<sizeof( $route_parts ); $i++ ) {
/*
* Compare the route part to the url part and see if they match
* or if the route part is {}
*/
if ( $i >= sizeof( $parts ) || ( $route_parts[ $i ] != '{}' & $route_parts[ $i ] != $parts[ $i ] ) ){
// Remove the route from the valid routes array
$valid_routes = array_values( array_diff( $valid_routes, [$route] ) );
}
}
}
// Find the route with the least occurrence of the {} characters
$route = $this->leastOccurrence( $valid_routes, '{}' );
if( $route != null ){
// Route found, output the route
echo 'Found route: ' . $route;
} else {
// No route found, 404
echo '404, not found';
}
这-简单来说-将给定的URL匹配到路由。输出为:
找到的路径:/ programs / {} / test / {}
我的程序的下一步是提取通配符字符串,本例中为'part_1'和'part_2'。我遇到的问题是我只是不知道从哪里开始,我没有任何逻辑可以解决,而这正是我真正想要的-与编码答案相反。