Ryan Armstrong
Ryan Armstrong

Reputation: 55

Regular expression that starts with a certain string and ignores those that contain a specific string

I am trying to write a regular expression in PHP that would match any string that contains 'search/site/*' but only if it does not contain the string 'ss_language'

Here is what I have so far: http://regexr.com?3416i This successfully matches any 'search/site/*' including 'search/site' so now I need the bit that excludes any string that contains 'ss_language'

Thinking about this, it seems that I could just nest another preg_match to just look for the ss_language, but is that the best way to go about it vs. one single regular expression? Is this even possible with one regular expression? Here are some examples and what they should return:

Thanks in advance for any help. I'm pretty new to these. Here is a failed attempt: http://regexr.com?3416f

Upvotes: 3

Views: 122

Answers (3)

kittycat
kittycat

Reputation: 15045

You don't need to use a regex which would be slower. Use strpos():

$status = (0 === strpos($url, 'search/site') && FALSE === strpos($url, 'ss_language'))
    ? 'PASS'
    : 'FAIL';

Check out the: DEMO

Basically what it does is it checks to see if the URL starts with search/site and if it does it then check to see if it does NOT contain ss_language and will return TRUE or FALSE or Pass/Fail in this example. Regex is not needed at all as you are just looking for substrings.

Upvotes: 0

FredericS
FredericS

Reputation: 413

You can check http://regexr.com?3417a for following regex:

^search/site/?(?:(?!ss_language).)*$

It's indeed using negative lookahead.

Upvotes: 0

rvalvik
rvalvik

Reputation: 1559

You can use a negative lookahead to assert that the string does not contain ss_language

^search/site/?(?!.*ss_language.*).*$

If you just want a true/false answer to whether or not it matches then you don't really need the .*$ (it would then only match search/site with the optional / given there is no ss_language anywhere in the string (short version):

^search/site/?(?!.*ss_language)

Upvotes: 2

Related Questions