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 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题