dirk
dirk

Reputation: 2306

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!

Upvotes: 3

Views: 1609

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627536

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/.+~'

Upvotes: 5

Related Questions