Search code examples
phpregexlookbehind

PHP Regex : several stopping characters with Positive lookbehind


Hi stackoverflow community !
I'm trying to use a simple regex expression in PHP based on a Positive lookbehind. My objective is to extract everything in a URL between a domain name and a set of specific characters (? or & or /). I want to extract "bar" on those examples :

  • foo.com/bar?
  • foo.com/bar&
  • foo.com/bar/

I tried

(?<=foo\.com\/)[^/?&]+  

it works fine in the plateform test but not with PHP 5.3x preg_match : the error thrown is that I can't use several stopping characters - it works with one.

I also tried a combination of positive lookbehind/lookahead, but the issue remains the same. What did I do wrong ?


Solution

  • In PHP, unlike (say) JavaScript, you can't use the regex-delimiter without escaping it, even inside a character class. So, you need to change this:

    "/(?<=foo\.com\/)[^/?&]+/"
    

    to this:

    "/(?<=foo\.com\/)[^\/?&]+/"