Sitthya Souvanlasy
Sitthya Souvanlasy

Reputation: 13

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 :

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 ?

Upvotes: 1

Views: 200

Answers (2)

Toto
Toto

Reputation: 91488

Escape the slashes:

preg_match("/(?<=foo\.com\/)[^\/?&]+/", "http://www.foo.com/bar?", $result);
                      here ___^

or use another delimiter

preg_match("#(?<=foo\.com/)[^/?&]+#", "http://www.foo.com/bar?", $result);

Upvotes: 1

ruakh
ruakh

Reputation: 183476

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\/)[^\/?&]+/"

Upvotes: 1

Related Questions