0

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.

3
Contributors
8
Replies
9
Views
5 Years
Discussion Span
Last Post by diafol
0

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

0

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;
}
?>

Edited by JACOBKELL: n/a

1

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
}
0

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.

0

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 ;)

0

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"; 	
}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.