Search code examples
phpregexslash

Regular expression for none or one slash in a string


I have some URLs like:

dir-1
dir-1/dir-2
dir-1/dir-2/dir-3
dir-1/dir-2/dir-3/dir-[n]..and so on..

My current regex (with PHP) looks like this:

/^([[:lower:][:digit:]\-\/]+)$/

So the regex matches all URLs. But in my case, I need only the first and second version, so that there is NONE or only one occurrence of a slash.

I tried multiple times to figure out the right way, but with no result.


Solution

  • Just match that set of characters (minus a /), then an optional /, then that set of characters again (optionally).

    /^([[:lower:][:digit:]-]+\/?[[:lower:][:digit:]-]*)$/