Say I have the following url:
/blog/this-is-a-post-20
and I want to separate it like this:
$urlTitle = "this-is-a-post";
$id = 20;
I'm currently trying the following:
Route::get('blog/{urlTitle}-{id}', function($urlTitle, $id)
But it's not working and it gives me:
$urlTitle = "this";
$id = "-is-a-post-20"
Route::get('blog/{urlTitle}-{id}', function($urlTitle, $id) {
var_dump($urlTitle); // this-is-a-post
var_dump($id); // 20
})->where('urlTitle', '.*');
This will make urlTitle
match the regular expression of 0+ characters. Expressions try to match as much as possible. That means it will first try to match this-is-a-post-20
and fail because the route can't continue to match -{id}
. It "backtracks" until it can find the -{id}
also.
To make this more efficient, replace the .*
regex with .*(?=-)
which will match 0+ characters followed by a -
. This will reduce the number of times the regular expression engine needs to backtrack.