2

Can anyone suggest how I would do this: Say if I had the string $text which holds text entered by a user. I want to use an 'if statement' to find if the string contains one of the words $word1 $word2 or $word3 . Then if it doesn't, allow me to run some code.

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

I need something like that.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Joey Morani
  • 25,431
  • 32
  • 84
  • 131
  • You want to run if all of them are absent, or atleast one of them is absent? – Dogbert Aug 06 '11 at 15:54
  • possible duplicate of [PHP - If string contains one of these words](http://stackoverflow.com/questions/6966490/php-if-string-contains-one-of-these-words) – hakre Aug 06 '11 at 15:58
  • @Joey Morani: Please don't duplicate questions. – hakre Aug 06 '11 at 15:59
  • Really sorry. The last question I made a mistake, so please if a mod could close/delete the last one. This one is much more helpful. – Joey Morani Aug 06 '11 at 16:10

6 Answers6

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

}
Dogbert
  • 212,659
  • 41
  • 396
  • 397
2

More flexibile way is to use array of words:

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

Result is: word1 exists in text

sasa
  • 2,443
  • 5
  • 23
  • 35
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
}
Gaurav Gupta
  • 5,380
  • 2
  • 29
  • 36
0

As in my previous answer:

if ($string === str_replace(array('@word1', '@word2', '@word3'), '', $string))
{
   ...
}
Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836
0

It may be better to use stripos instead of strpos because it is case-insensitive.

gmadd
  • 1,146
  • 9
  • 18
Sergiy T.
  • 1,433
  • 1
  • 23
  • 25
0

you can use preg_match, like this

if (preg_match("/($word1)|($word2)|($word3)/", $string) === 0) {
       //do something
}
laurac
  • 429
  • 5
  • 11