Reputation: 26581
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
Reputation: 1453
It may be better to use stripos
instead of strpos
because it is case-insensitive.
Upvotes: 0
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
Reputation: 429
you can use preg_match, like this
if (preg_match("/($word1)|($word2)|($word3)/", $string) === 0) {
//do something
}
Upvotes: 0
Reputation: 197574
As in my previous answer:
if ($string === str_replace(array('@word1', '@word2', '@word3'), '', $string))
{
...
}
Upvotes: 0
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
Reputation: 222040
if ( strpos($string, $word1) === false && strpos($string, $word2) === false && strpos($string, $word3) === false) {
}
Upvotes: 2