...

View Full Version : How do I find a word in a sentence from the list of words in an array?



curb
07-27-2007, 09:17 PM
I have few list of words (needle) I want to find in a sentence (haystack). After a word is found, how would I echo that word? Is there a way to have a multi array so:

if the sentence contains word1,word2 or word3 then echo "coding"
if the sentence contains word4,word5 or word6 then echo "forums"


<?php
$title_of_the_item = "This would be the sentence being pulled.";
$words_from_title = explode(" ", $title_of_the_item);

$word = array("structure", "php", "sentence", "pulled");

if(in_array($word,$words_from_title)){
//even though two words are found in the array, use only 1
}
?>

enoyhs
07-27-2007, 09:53 PM
Firstly I want to ask why do you want to break a string into array?
If it is not really needed I think I would use this code:


<?php
$title_of_the_item = "This would be the sentence being pulled.";

$word = array("structure", "php", "sentence", "pulled");

if((strpos($title_of_the_item,$word[1])||strpos($title_of_the_item,$word[2])||strpos($title_of_the_item,$word[3]))>0 ){
echo "coding";
} elseif ((strpos($title_of_the_item,$word[4])||strpos($title_of_the_item,$word[5])||strpos($title_of_the_item,$word[6]))>0 ) {
echo "forums";
}
?>


I'm sure there are some shorter way but this was the first one I though about...



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum