I just have a little trouble with the symfony regex pattern in a routing config.
我对路由配置中的symfony正则表达式模式有点麻烦。
I would like to match both /keyword
and /keyword/
URLs. The /
character is optional.
Here is my pattern :
我想匹配/ keyword和/ keyword / URL。 /字符是可选的。这是我的模式:
pattern: /{keyword}/?
/keyword/
matches the pattern, while /keyword
does not.
/ keyword /匹配模式,而/ keyword则不匹配。
How should I write the pattern ?
我该怎么写这个模式?
3 个解决方案
#1
5
If you add the trailing slash, it is optional — a user will be redirected from the path without the slash to the path with it. So, the /{keyword}/
pattern will work for both /{keyword}
and /{keyword}/
.
如果添加尾部斜杠,则它是可选的 - 用户将从没有斜杠的路径重定向到带有它的路径。因此,/ {keyword} / pattern适用于/ {keyword}和/ {keyword} /。
However, if you define it without the trailing slash — /{keyword}
— it will work for /{keyword}
only.
但是,如果您定义它而没有斜杠 - / {keyword} - 它仅适用于/ {keyword}。
#2
0
I don't think you can have a RegEx pattern in a route. The keyword
can be required to have a specific RegEx pattern, but that's a different matter.
我认为您不能在路线中使用RegEx模式。关键字可能需要具有特定的RegEx模式,但这是另一回事。
If you're using YML, then I think the best thing to do is to have two different routes:
如果您正在使用YML,那么我认为最好的办法是拥有两条不同的路线:
route1:
pattern: /{keyword}
...
route2:
pattern: /{keyword}/
...
If you're using annotations, you can put them both at the top of the controller action:
如果您正在使用注释,则可以将它们放在控制器操作的顶部:
/**
* @Route("/{keyword}");
* @Route("/{keyword}/");
*/
#3
0
In the controller where your function is use the annotations :
在您的函数使用注释的控制器中:
/**
* Function
*
*
* @Route("your/route/{keyword}")
* @Route("your/route/{keyword}/")
*/
And you'll be able to access to this function with both routes.
并且您将能够使用这两个路径访问此功能。
#1
5
If you add the trailing slash, it is optional — a user will be redirected from the path without the slash to the path with it. So, the /{keyword}/
pattern will work for both /{keyword}
and /{keyword}/
.
如果添加尾部斜杠,则它是可选的 - 用户将从没有斜杠的路径重定向到带有它的路径。因此,/ {keyword} / pattern适用于/ {keyword}和/ {keyword} /。
However, if you define it without the trailing slash — /{keyword}
— it will work for /{keyword}
only.
但是,如果您定义它而没有斜杠 - / {keyword} - 它仅适用于/ {keyword}。
#2
0
I don't think you can have a RegEx pattern in a route. The keyword
can be required to have a specific RegEx pattern, but that's a different matter.
我认为您不能在路线中使用RegEx模式。关键字可能需要具有特定的RegEx模式,但这是另一回事。
If you're using YML, then I think the best thing to do is to have two different routes:
如果您正在使用YML,那么我认为最好的办法是拥有两条不同的路线:
route1:
pattern: /{keyword}
...
route2:
pattern: /{keyword}/
...
If you're using annotations, you can put them both at the top of the controller action:
如果您正在使用注释,则可以将它们放在控制器操作的顶部:
/**
* @Route("/{keyword}");
* @Route("/{keyword}/");
*/
#3
0
In the controller where your function is use the annotations :
在您的函数使用注释的控制器中:
/**
* Function
*
*
* @Route("your/route/{keyword}")
* @Route("your/route/{keyword}/")
*/
And you'll be able to access to this function with both routes.
并且您将能够使用这两个路径访问此功能。