Search code examples
regexzend-frameworkzend-route

zend regex route with negative lookahead


I'm trying to write a regex route in zend (1.11) that matches urls ending in /foo but not if they start with /bar e.g.

/foo - match
/any/words/foo - match

/any/words - no match (doesn't end in /foo)
/any/words/barfoo - no match (doesn't end in /foo)
/bar/foo - no match (starts with /bar)
/bar/any/words/foo - no match (starts with /bar)

my regext route looks like this:

'^foo$|^(?!/bar/).+/foo$'

But I find it matches anything ending in /foo, even if it starts with /bar.


Solution

  • Final solution:

    '^foo$|^(?!bar).*/foo$'
    

    Explanation The regex was a red-herring, this was more of a zend problem. My problem was that the url string that is passed to Zend doesn't contain a leading slash, so I was testing regex against the wrong input. So in my solution I need to look for '^foo$' to match '/foo' OR '^(?!bar).*/foo$' to match '/any/words/foo' excluding '/bar/any/words/foo'.

    Special thanks however to @zx81 for an amazingly fast and detailed response, and helping un-block my thinking. I'd recommend reading his response above for reference.