2011-08-06 155 views
2

任何人都可以建议我如何做到这一点:说如果我有字符串$text,其中包含用户输入的文本。我想使用'if语句'来查找字符串是否包含$word1$word2$word3之一。如果没有,请允许我运行一些代码。查找字符串中的单词

if (strpos($string, '@word1' OR '@word2' OR '@word3') == false) { 
    // Do things here. 
} 

我需要类似的东西。

+0

你想运行,如果所有的人缺席,或者其中至少有一个缺席? – Dogbert

+0

可能重复的[PHP - 如果字符串包含这些词之一](http://stackoverflow.com/questions/6966490/php-if-string-contains-one-of-these-words) – hakre

+0

@Joey Morani:请不要重复提问。 – hakre

回答

2

更多flexibile方法是使用单词的数组:

$text = "Some text that containts word1";  
$words = array("word1", "word2", "word3"); 

$exists = false; 
foreach($words as $word) { 
    if(strpos($text, $word) !== false) { 
     $exists = true; 
     break; 
    } 
} 

if($exists) { 
    echo $word ." exists in text"; 
} else { 
    echo $word ." not exists in text"; 
} 

的结果是:在文本

2
if (strpos($string, $word1) === false && strpos($string, $word2) === false && strpos($string, $word3) === false) { 

} 
0

存在正如我previous answer字1:

if ($string === str_replace(array('@word1', '@word2', '@word3'), '', $string)) 
{ 
    ... 
} 
0

可能更好地使用stripos而不是strpos,因为它是ca SE-不敏感。

0

你可以使用的preg_match,这样

if (preg_match("/($word1)|($word2)|($word3)/", $string) === 0) { 
     //do something 
} 
1

定义以下功能:

function check_sentence($str) { 
    $words = array('word1','word2','word3'); 

    foreach($words as $word) 
    { 
    if(strpos($str, $word) > 0) { 
    return true; 
    } 
    } 

    return false; 
} 

并调用它像这样:

if(!check_sentence("what does word1 mean?")) 
{ 
    //do your stuff 
}