dirk dirk - 1 year ago 109
PHP Question

preg_match wildcard, require at least one character

The preg_match below matches 'empty' (0 characters) against the wildcard. I want to disable that:

preg_match('/site.com\/subsection\/.*?/', $page_url);

So the thing above should match site.com/subsection/subpage, but shouldn't match the root dir site.com/subsection/

How can I adjust the regex above? Thanks in advance!

Answer Source

The .*? at the end of the pattern matches empty string. You need to make it match one or more characters using .+:


Now, it requires at least 1 char after site.com/subsection/.

Note the dot must be escaped to match a literal dot.

Also, it might be a good idea to use regex delimiters other than / (as OcuS suggests in the comments below) if you have many slashes in the pattern itself. I usually use tildes:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download