Shafizadeh Shafizadeh - 1 year ago 39
PHP Question

How to check string is containing a word and isn't containing another word?

I have a string like this:

$str = "this is a test";

I want to validate
and return true if string is containing
and it isn't containing
. How can I do that?


"this is a test" // false
"this is a tes" // true "is" exists and "test" doesn't exist
"this iss a tes" // false
"this iss a test" // false

Here is my pattern
. But it seems to just checks existing, I mean it also returns true when
exists. I mean the result of following code us true which shouldn't be (because

if (preg_match ("/\bis\b(?!test)/","this is a test")) {
return true;
} else {
return false;

Note: I'm really insist on doing that by regex.

Jan Jan
Answer Source

This is how it can be done:


See a demo on
This looks for is as a single word and makes sure test can not be found afterwards (using a negative lookahead, combined with anchors).

Be aware though, that strings like this test is will still be matched, ie. the order of the words matters with this expression!