从鼻涕虫身上查到他的身份


Get the id from a slug Laravel 4

我使用的是Laravel 4.1。所以我想用这个结构来创建URL: domain。Tld/macbook-pro-2389并使用此路由:

  Route::get('{sc}-{id}', 'ProductController@getDetails')
  ->where('id', ''d+');

但问题是我不能得到确切的Id时,鼻涕虫包含多个破折号。

我怎样才能做到这一点,并保持相同的结构?

编辑

到目前为止,我所做的唯一解决方案是用这个正则表达式([a-z0-9'-]+)'-([0-9]+)验证整个弹头,然后我爆炸弹头以获得像这样的最后一项:

 $id = explode('-', $slug);
 $id = end($id);
 Route::get('{slug}', function($slug){
 $id = explode('-', $slug);
 //  2389
 $idOnly = array_pop($id);
 // macbook-pro
 $nameDashes = implode('-', $id);
// It is possible to pass $idOnly and $nameDashes to `ProductController@getDetails` ?
 })
 ->where('slug', '([a-z0-9'-]+)'-([0-9]+)');

您可以通过定义scid来解决这个问题:

Route::get(
    '{sc}-{id}',
    function($sc, $id) {
        var_dump($sc);
        var_dump($id);
        exit;
    }
)
    ->where('sc', '.*?')
    ->where('id', ''d+');

在这种情况下,我将惰性地匹配任何数量的字符。由于它是惰性的,它将一直执行,直到看到-后面跟着1+个数字。

最后解析一个正则表达式,类似于:

^        (?# start of URL)
(.*?)    (?# capture sc)
-        (?# delimiter)
('d+)    (?# capture id)
$        (?# end of URL)