dirk dirk - 9 days ago 6
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

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

'/site\.com\/subsection\/.+/'
                         ^

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:

'~site\.com/subsection/.+~'
Comments