I have following code which check does targeted word exits in sentence and it's working.

$text = "blablavalueblabla";
$word = "value";

$pos = strpos($text, $word);
if ($pos === false) {
    echo "You word is found in this sentence";

} else {
   echo "Your word it's not found in this sentence";

}

But,what i need to add to make it possible with multiple values?
Something like:
$word = "value OR value2 OR value3 OR value4 OR etc";
As you can see i tried with OR,with ||,and with some other combinations but nothing worked.So i want to check more words which i stated are they present in sentence.

Recommended Answers

All 8 Replies

I see some functions which might do that,but dont know how to output them.

Actually,i think this should do:

function strpos_arr($haystack, $needle) {
    if(!is_array($needle)) $needle = array($needle);
    foreach($needle as $what) {
        if(($pos = strpos($haystack, $what))!==false) return $pos;
    }
    return false;
}
$pos = strpos_arr('sentence with word', array('word', 'wordtwo', 'wordthree'));
if ($pos === false) {
    echo "Word is not found in sentence";
	//return false;
} else {
   echo "Word is found in sentence";
   // return true;
}
?>
Member Avatar for diafol

Solved?

If you only want to know if the word is there, and not need its position, then preg_match() will do the trick.

if (preg_match('%\b(word|wordtwo|wordthree)\b%i', $text) > 0) {
  // one of the words was found
}

If you only want to know if the word is there, and not need its position, then preg_match() will do the trick.

if (preg_match('%\b(word|wordtwo|wordthree)\b%i', $text) > 0) {
  // one of the words was found
}

Seems that works only if $text = word,if it's $text = blaword or $text = wordbla it does not work,in shortly works for exact match only not partial.

Actualy found correct solution:

if (preg_match('/wordone|wordtwo/', $text))
	
	{
	echo "Word is not found";
}
  else
{
	echo"Word is not found"; 	
}

So in shortly,unless someone have shorter code of this,consider this resolved ;)

Member Avatar for diafol

As Prit (+1 for his suggestion!) states preg_match could be a cooler solution. strpos() is quicker, BUT looping strpos vs. preg_match would probably be slower.

For an array of values:

$wordarray = array('check','cheque','czech');
$pattern = implode("|",$wordarray);
if (preg_match("/($pattern)/", $text)){
   echo "Word is not found";
}else{
    echo"Word is not found"; 	
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.