HaLo2FrEeEk Posted February 16, 2009 Share Posted February 16, 2009 I'm updating my site's layout and adding a search box. I thought I had the code for it all squared away until I realized that there was a fundamental problem with it. Right now this is how I have my query: SELECT * FROM `news` WHERE `news_title` LIKE '% ".$find." %' OR `news_text` LIKE '% ".$find." %' ORDER BY `news_id` DESC $find is the php variable I'm passing from the search form. Anyways, you'll notice how it looks for "[space][search text][space]". Well what if the text you're searching for is the first or last word or words of the title or news content? For example, I have a title called "Halo Wars Demo Cutscenes in HD", so a search for "Halo Wars" should have returned that news post, but it doesn't. A search for Wars returns 2 results, the above titled, and one about Star Wars: The Force Unleashed. How could I overcome this problem without removing the space from the query? If I remove the space then a search for the word "read" would return results with th eword "thread" because "thread" contains the word "read". How can I fix that? Link to comment https://forums.phpfreaks.com/topic/145402-solved-making-a-search-on-my-site/ Share on other sites More sharing options...
HaLo2FrEeEk Posted February 16, 2009 Author Share Posted February 16, 2009 Nevermind, I solved it myself. Here is the modified code I used: On the PHP side I had to seperate the words in the search string and add [[:<:]] and [[:>:]] to the beginning and end of each, respectively, then trim the whitespace off the end: $findarr = explode(" ", $find); foreach($findarr as $word) { $searchstr .= "[[:<:]]".$word."[[:>:]] "; } $searchstr = trim($searchstr); Then I had to change my query a little: SELECT * FROM `news` WHERE `news_title` REGEXP '".$searchstr."' OR `news_text` REGEXP '".$searchstr."' ORDER BY `news_id` DESC And that did the trick. REGEXP treats [[:<:]] and [[:>:]] like the beginning and end of a word, no matter what. So I just had to padd each word with those on the beginning and end and insert a space in between words, trim off the last space and I was golden. Returns results where the word being searched for is a whole word, meaning searching for "read" will not return "thread", and searching for a word at the beginning of a sentence will work just fine. Link to comment https://forums.phpfreaks.com/topic/145402-solved-making-a-search-on-my-site/#findComment-763337 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.