Shafizadeh
Shafizadeh

Reputation: 10380

How can I match something if it doesn't contain specific word?

Here is my string:

$str = "this is a string
        this is a test string";

I want to match everything between this and string words (plus themselves).

Note: between those two words can be everything except the word of test.

So I'm trying to match this is a string, but not this is a test string. Because second one contains the word of test.


Here is my current pattern:

/this[^test]+string/gm

But it doesn't work as expected

How can I fix it?

Upvotes: 3

Views: 103

Answers (2)

user3215326
user3215326

Reputation:

The way you did it it was excluding any characters in the list "test". The way to do this would be using negative lookarounds. The regex would then look like this.

this((?!test).)*string

Upvotes: 2

mrid
mrid

Reputation: 5796

If you want to do this without regex, you can use fnmatch()

function match($str)
{
    if (strpos($str, 'test') == false) /* doesn't contain test */
    {
        if (fnmatch('this*string', $str))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    else
        return false;
}

Upvotes: -1

Related Questions