Quick regex question (include empty string)

Don’t believe there’s a thread for regex alone, however, I am programming in PHP. I am blacklisting a directory and any of its subdirectories of /cms/plus/anything/past/it/. cms/(.*) works perfectly except for the very root of /cms/. How can I get it to include an empty string in the expression?

Doesn’t fit my situation. My string: “cms/(.*)” This regex expression makes it so that in my application, the following urls are blocked correctly:

/cms/test1
/cms/whatever/i/put/in/past/cms

However, if I simply go to /cms/, then it doesn’t work because the regex part ‘(.*)’ expects a non null string. I need that regex expression to include a null string.

substr($string, 0, 3) == ‘cms’ should also work, no? :slight_smile:

Okay, but for the exaples you give substr($path, 0, 4) == '/cms' would also work, wouldn’t it?

I really don’t see the need for regex if all you care about is a fixed set of characters at the start of the string (“/cms”) – that’s exactly what substr is for.

If you want to do it in regex, remove the / between “cms” and “(.*)”

This is a line from a specific plugin of Zend Framework which might be why it doesn’t make sense by itself. substr() isn’t possible where I would be utilizing it. Also I’ve thought of doing ‘cms(.*)’ however if there is a url of say ‘/cmswhatever’, it would also be included in the expression and break my application.

So I take it there is no regex expression to include null data?

Ah that makes sense! :slight_smile:

(.*) should include the null string though:


var_dump(preg_match('~cms/(.*)~', '/cms/', $m));

var_dump($m);

/**
int(1)
array(2) {
  [0]=>
  string(4) "cms/"
  [1]=>
  string(0) ""
}
**/

If that doesn’t work you might try (.)? instead of just (.) but that shouldn’t be necessary

‘cms(/.*)?’ gave me the desired result I was looking for.