dp7311
dp7311
2016-05-31 13:00

如何检查字符串是否包含一个单词并且不包含另一个单词?

  • regex
  • string
  • php

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.

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

6条回答