如何检查字符串是否不包含某个单词?

时间:2013-12-17 14:01:10

标签: php

我想检查字符串是否包含我到目前为止的两个单词:

if (strstr($Description1,'word1') or strstr($Description1,'word2') ){ 
do Action 1
} else 
Action 2

问题是如果它不包含2个单词,它会检查单词,但是我想要执行操作1。如果确实包含2个单词,它会在第1分钟执行操作。

欢迎任何帮助

6 个答案:

答案 0 :(得分:4)

你说过,你想要反对当前的行为 - >你必须否定现状:

if (! (strstr($Description1,'word1') or strstr($Description1,'word2') )){ 
do Action 1
} else 
Action 2

由于De Morgan's law将成为:

if (!strstr($Description1,'word1') and !strstr($Description1,'word2') ){ 
do Action 1
} else 
Action 2

答案 1 :(得分:2)

if (!strstr($Description1,'word1') and !strstr($Description1,'word2') ){ 
do Action 1
} else 
Action 2

答案 2 :(得分:1)

 if(strpos($Description1, 'word1') !== FALSE || strpos($Description2, 'word2') !== FALSE)     
 {

 } else {

 }

答案 3 :(得分:1)

这是一个基本的布尔错误。你想确保:

  • “word1”在字符串 AND
  • “word2”在字符串中是 NOT

试试这个:

if (!strstr($somestring, "word1") && !strstr($somestring, "word2")) {
    // $somestring does not contain "word1" and "word2"
} else {
    // $somestring contains "word1", "word2" or both
}

来自documentation但是:

  

如果您只想确定特定针是否出现在haystack中,请使用速度更快且内存不足的函数strpos()

答案 4 :(得分:0)

您可以轻松地在else块中交换代码。这将扭转这种情况:)

更好的方法可能是否定实际情况。为此,您可以在条件表达式中添加!字符。

if ( condition == true ){
  // condition is equal to a "true" value
}

if ( !condition == true ){
  // condition is NOT equal to a "true" value
}

否定!几乎意味着返回任何布尔结果,使用相反的方法。

答案 5 :(得分:0)

您也可以在foreach循环中执行此操作,以便更好地阅读和稍后编辑:

<?php

$words = array( 'word1', 'word2' );
$Description1 = 'My word1';

$found = 0;
foreach( $words as $word )
    if ( strpos( $Description1, $word ) !== false )
        $found++;

switch ( $found ) {
    case 1:
        // Action
        break;
    case 2:
        // Action
        break;
    default:
        echo $found . ' found.';
        break;
}

?>
相关问题