hay there How can i check for say 2 or more words in a string... Imagine a search engine type scenario where the user enters a number of keywords to search Now I know this checks for 2 words on a "OR" basis if(preg_match("/$findthis|$this/i", $text_to_search)) { //do something } PHP: So this ill check to see if the $text_to_search PHP: contains either $findthis PHP: or $this PHP: but i need it to check with the "and" operator - so for example.. search $text_to_search PHP: for $findthis PHP: and $this PHP: how can i do this? many thanks
this wont work for my needs as the amount of words entered will be user dependent - like a search engine thanks though
Hay that worked perfect thanks - this also works.. if(preg_match("/$findthis.+.$this/i", $text_to_search)) { // do stuff } Code (markup): I created this function to work with my script function SplitQuery($this_query) { $all_words = explode(" ", $this_query); // Get each word from query foreach($all_words as $val => $word) // Loop through each word { $toreturn = $toreturn . $word.".+."; // Add '.+.' for preg_match } $preg_stuff = trim($toreturn, ".+."); // trim of the end return $preg_stuff; //Return all words example: word1.+.word2.+.word3 } Code (markup): then if(preg_match("/".SplitQuery($query)."/i", $news_headline." ".$news_content)) { //Do stuff } Code (markup): another way i was told was this function SearchQuery($this_query, $to_search) { $searchTerms = explode(" ", $this_query); $allMatched = 1; foreach ($searchTerms as $searchTerm) { if ( preg_match('/'.$searchTerm.'/i',$to_search) == false ) { $allMatched = 0; } } return $allMatched; } Code (markup): But i think thats very long winded over samyaks way thanks so much :0)
John, you can make your 'SplitQuery' function like this: function SplitQuery($this_query) { $all_words = explode(" ", $this_query); // Get each word from query $preg_stuff = implode(".+.", $all_words); return $preg_stuff; //Return all words example: word1.+.word2.+.word3 } PHP: However I think you will still need to remove special characters such as '.', '/', etc from each of your words. If not, they will interfere with the preg_matches.
hi.. cheers for that i had been told this may cause issues if special charters are entered also some people have mentioned speed issues in regards to preg_match say next to stripos ... i have no idea about speed but would love to hear your recommendations I have this code which also works well function matchWords($findtheseItems, $text_to_search) { $items = explode(" ", $findtheseItems); foreach ($items as $item) { if(stripos($text_to_search, $item) === false) { return false; } } return true; } Code (markup):