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


How to check if a string does not contain a certain word?

我想检查一个字符串是否不包含两个单词:

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

问题是它确实检查了单词,但如果它不包含这两个单词,我想做动作1。此时,如果它确实包含这两个单词,则执行动作1。

欢迎提供任何帮助

你说过,你想做出与当前行为相反的行为->你必须否定当前条件:

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

根据德摩根定律,它将变成:

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

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

  • 字符串AND中的"word1"为NOT
  • 字符串中的"word2"不是

试试这个:

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

不过,从文件来看:

如果您只想确定大海捞针中是否出现了特定的指针,请使用速度更快、内存占用更少的函数strpos()。

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

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

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

否定的!几乎意味着无论返回什么布尔结果,都要使用相反的结果。

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

您也可以在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;
}
?>