Shafizadeh Shafizadeh - 6 months ago 9
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
$str
and return true if string is containing
is
and it isn't containing
test
. How can I do that?




Examples:

"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
\bis\b(?!test)
. But it seems to just checks existing, I mean it also returns true when
test
exists. I mean the result of following code us true which shouldn't be (because
test
exists)
.

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

This is how it can be done:

^.*?\bis\b(?:(?!\btest\b).)*$

See a demo on regex101.com.
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!