php - How to only allow certain number of forward slashes using regular expression? -


i'm routing application , i'd allow maximum of 2 directory subpaths following directory path of tags/. hyphens , alnums allowable characters.

the following validate , bolded below returned router single match:

  • tags/how-to-bake
  • tags/how-to-bake/cookies

if there more 2 subpaths (or 2 or more slashes, in other words) router should return no match.

my server redirects on trailing slashes (to non-trailing slash url) don't need taken consideration.

i'm using tags/([\w+\-\/]+)$ allow infinitely many subpaths, , forced check subpath length (forward slash count) after router returns match.

i'm not sure how can allow 0 or 1 forward slashes in character set wrote, while having word characters possibly follow, , have them returned single match.

is possible regular expression?

barmar's solution answers question perfectly... version taking in account trailing slash in path's expression:

(tags\/[-\w]+\/?(?:[-\w]+)?(?<!\/)\/?)$ 

regex101.com


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -