使用正则表达式匹配 Laravel 路由中的子字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27198019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using a regex to match a substring in a Laravel route
提问by prograhammer
My URL is: www.foo.com/some-bar-slug-here/page
我的网址是:www.foo.com/some-bar-slug-here/page
I can't get a route to catch if the string "bar" is found in the slug shown above:
如果在上面显示的 slug 中找到字符串“bar”,我将无法获得一条路线:
Route::any('{myslug}/page/', array('as'=>'bar-page', 'uses'=>'Controllers\MyBar@index'))
->where('myslug','/bar/');
If I use the regex expression [0-9A-Za-z\-]+
it works, but it doesn't work for /bar/
. Any ideas?
如果我使用正则表达式[0-9A-Za-z\-]+
它可以工作,但它不适用于/bar/
. 有任何想法吗?
回答by prograhammer
I got it working with ^([0-9A-Za-z\-]+)?bar([0-9A-Za-z\-]+)?
我得到它的工作 ^([0-9A-Za-z\-]+)?bar([0-9A-Za-z\-]+)?
So the updated route code looks like this:
所以更新后的路由代码如下所示:
Route::any('{myslug}/page/', array('as'=>'bar-page', 'uses'=>'Controllers\MyBar@index'))
->where('myslug','^([0-9A-Za-z\-]+)?bar([0-9A-Za-z\-]+)?');
Bonus: To make it case insensitive, I do this: ^([0-9A-Za-z\-]+)?(?i)bar([0-9A-Za-z\-]+)?
奖励:为了不区分大小写,我这样做: ^([0-9A-Za-z\-]+)?(?i)bar([0-9A-Za-z\-]+)?
Note: If you are using a copy of this route further down in the your routes file, but searching for a different sub-string then you will need to name your {myslug}
to something different like {myslug2}
, otherwise Laravel will not run all of the routes.
注意:如果您在路由文件中使用此路由的副本,但要搜索不同的子字符串,则需要将其命名{myslug}
为不同的名称,例如{myslug2}
,否则 Laravel 将不会运行所有路由。