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

时间:2016-05-31 13:00:03

标签: php regex string

我有一个这样的字符串:

$str = "this is a test";

如果字符串包含$str且未包含is,我想验证test并返回 true 。我怎么能这样做?

示例:

"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

这是我的模式\bis\b(?!test)。但它似乎只是检查现有的,我的意思是当test存在时它也返回 true 。我的意思是跟随代码我们 true 的结果,它不应该是(因为test存在)

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

注意:我真的坚持用正则表达式做到这一点。

6 个答案:

答案 0 :(得分:3)

使用strpos

$str = "this is a test";
if (strpos($str, 'is') !== false && strpos($str, 'test') === false ) {
   return true;
} else {
  return false;
}

答案 1 :(得分:2)

尝试使用正面和负面的外观:

^(?=.*\bis\b)(?!.*\btest\b).*

解释

^              # stands for start of the string, both lookahed below will use it as anchor

(?=            # positive lookahed
    .*         # can have any amount of characters till
    \bis\b     # literal text "is" with boundaries
)              # if not succeed will fail the regex

(?!            # negative lookahead
    .*         # can have any amount of characters till
    \btest\b   # literal text "test" with boundaries
)              # if succeed will fail the regex

.*             # if the regex didn't fail till here, match all characters in this line

答案 2 :(得分:1)

^(?!.*\btest\b).*\bis\b.*$这样的东西就是:

if (preg_match ("(^(?!.*\btest\b).*\bis\b.*$)","this is a test")) {
    return true;
} else {
    return false;
}

好的解释那么,虽然很明显,它首先检查'test'并不存在任何数量的字符,然后确保'is'确实存在。

答案 3 :(得分:1)

请试试这个 ^ \双\湾?(?:?!(\ BTEST \ b))的 $

答案 4 :(得分:1)

你可以这样做:

^                       # anchor it to the beginning of the line
    (?:(?!\btest\b).)*  # makes sure no test can be matched
    \bis\b              # match is as a word
    (?:(?!\btest\b).)*  # same construct as above
$                       # anchor it to the end of the line

a demo on regex101.com

对于PHP代码,请参阅以下代码段:

<?php
$string = "this is a test
this is a tes
this iss a tes
this iss a test
this test is";

$regex = '~
            ^                       # anchor it to the beginning of the line
                (?:(?!\btest\b).)*  # makes sure no test can be matched
                \bis\b              # match is as a word
                (?:(?!\btest\b).)*  # same construct as above
            $                       # anchor it to the end of the line
          ~mx';

preg_match_all($regex, $string, $matches);
print_r($matches);
?>

提示: 请注意,在接受原始答案中的错误后,我已更改了答案。)

答案 5 :(得分:0)

尝试使用正则表达式

正常工作
 $str = "this is a test";

     if (preg_match ("/is/",$str) && !preg_match ("/test/",$str)) {
      return false;
    } else {
        return true;
    }