Question

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.

Was it helpful?

Solution

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

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

OTHER TIPS

You could just explode the string using the slash as the delimiter -

$str = "dir-1/dir-2";    
$splitArr = explode('/',$str);
  • If the resulting array has more than one element then a slash is present.
  • More than two elements == more than one slash!
array (
  0 => 'dir-1',
  1 => 'dir-2',
)  

As your question states you are not talking about any old string variable buy specifically URL's, make sure to remove the http or https protocol from the beginning of the string :

Eg: https://marvin.com/dir-1/dir-2

You could possibly use the $_SERVER[REQUEST_URI] variable - this returns the current URL relative to the sites DOCUMENT ROOT.

So the $_SERVER[REQUEST_URI] of https://marvin.com/dir-1/dir-2 would be :

/dir-1/dir-2 (look familiar?)

After the explode() you could also use array_shift() to remove the initial root slash and
HEY PRESTO! you have avoided using regular expressions!

Some people, when confronted with a problem, think “I know, I'll use regular expressions.” Now they have two problems.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top