Joey Morani
Joey Morani

Reputation: 26581

Finding words in a string

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.

Upvotes: 2

Views: 303

Answers (6)

Sergiy T.
Sergiy T.

Reputation: 1453

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

Upvotes: 0

Gaurav Gupta
Gaurav Gupta

Reputation: 5416

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
}

Upvotes: 1

laurac
laurac

Reputation: 429

you can use preg_match, like this

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

Upvotes: 0

hakre
hakre

Reputation: 197574

As in my previous answer:

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

Upvotes: 0

sasa
sasa

Reputation: 2443

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

Upvotes: 2

Dogbert
Dogbert

Reputation: 222040

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

}

Upvotes: 2

Related Questions