2

誰でも私がこれを行う方法を提案できますか:$textユーザーが入力したテキストを保持する文字列があるとします。「if ステートメント」を使用して、文字列に単語$word1 $word2またはのいずれかが含まれているかどうかを確認したいと考えています$word3。そうでない場合は、コードを実行させてください。

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

私はそのようなものが必要です。

4

6 に答える 6

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 がテキストに存在する

于 2011-08-06T15:59:38.070 に答える
2
if ( strpos($string, $word1) === false && strpos($string, $word2) === false && strpos($string, $word3) === false) {

}
于 2011-08-06T15:52:55.827 に答える
1

Define the following function:

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

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

  return false;
}

And invoke it like this:

if(!check_sentence("what does word1 mean?"))
{
  //do your stuff
}
于 2011-08-06T16:13:10.090 に答える
0

私の前の答えのように:

if ($string === str_replace(array('@word1', '@word2', '@word3'), '', $string))
{
   ...
}
于 2011-08-06T16:00:52.697 に答える
0

大文字と小文字が区別されないため、stripos代わりに使用する方がよい場合があります。strpos

于 2011-08-06T16:01:35.000 に答える
0

このようにpreg_matchを使用できます

if (preg_match("/($word1)|($word2)|($word3)/", $string) === 0) {
       //do something
}
于 2011-08-06T16:08:21.400 に答える