Symfony regex: how to write an optional character?

I just have a little problem with the symfony regex pattern in the routing configuration.

I would like to match the URLs /keyword and /keyword/ . The symbol / is optional.
Here is my template:

 pattern: /{keyword}/? 

/keyword/ matches the pattern, but /keyword doesn’t.

How to write a template?

+4
source share
3 answers

If you add a trailing slash, this is not necessary - the user will be redirected from the path without a slash to the path with it. Thus, the template /{keyword}/ will work for both /{keyword} and /{keyword}/ .

However, if you define it without a trailing slash - /{keyword} - it will only work for /{keyword} .

+5
source

I don’t think you might have a RegEx pattern in the route. keyword may need to have a specific RegEx pattern, but that's another matter.

If you are using YML, I think it is best to have two different routes:

 route1: pattern: /{keyword} ... route2: pattern: /{keyword}/ ... 

If you use annotations, you can put them at the top of the controller action:

 /** * @Route("/{keyword}"); * @Route("/{keyword}/"); */ 
0
source

In the controller, where your function uses annotations:

 /** * Function * * * @Route("your/route/{keyword}") * @Route("your/route/{keyword}/") */ 

And you can access this feature using both routes.

0
source

Source: https://habr.com/ru/post/1437600/


All Articles