在字符串中查找单词

时间:2011-08-06 15:51:12

标签: php strpos

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

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

我需要这样的东西。

6 个答案:

答案 0 :(得分:2)

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

}

答案 1 :(得分:2)

更灵活的方式是使用单词数组:

$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";
}

结果是:word1存在于文本

答案 2 :(得分: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
}

答案 3 :(得分:0)

与我的previous answer

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

答案 4 :(得分:0)

最好使用stripos代替strpos,因为它不区分大小写。

答案 5 :(得分:0)

你可以像这样使用preg_match

if (preg_match("/($word1)|($word2)|($word3)/", $string) === 0) {
       //do something
}
相关问题