dp7311 2016-05-31 13:00
浏览 141
已采纳

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

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条回答 默认 最新

  • douzhi7082 2016-05-31 13:17
    关注

    You can do it like this:

    ^                       # 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
    

    See a demo on regex101.com.

    For a PHP code, see the following snippet:

    <?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);
    ?>
    

    Hint: Note that I have changed the answer after it has been accepted to correct flaws in the original answer).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM