A decent search function is a must for any serious site. There are countless ways to add search to your site, some very simple and some quite complicated. You can use a hosted service (like Google), a third-party script or you can design your own. If the latter interests you, I offer some sample code that I developed for this site, albeit in a slightly simplified form.
There are many features that can be included or omitted from a search script. Naturally, each feature adds complexity. The features that I think are most useful in a search function include:
- An “advanced search” form displaying all the advanced search options
- Boolean search choices (exact term, all terms, any terms)
- Fields (and/or tables) to include in the search
- Some sort of relevancy scoring to prioritize results
- Sorting options (relevancy is the default, but others may be appropriate for your situation, such as title, posted date, etc.)
- Multi-page results display and user option to choose number of results to display per page
- Highlighted context text (several words before and after the searched for term(s) to provide some context to the result)
Below is the code (both some basic CSS styling and the core PHP code)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | <style> #searchform-advanced form { border-top: 3px solid #ccc; border-bottom: 3px solid #ccc; background: #f3f3f3; padding: 10px; margin-top:10px; } #searchform-advanced h1 { color: #993333; border-bottom: 1px dotted #993333; } h2, #searchform-advanced h2 { color: #abc; font-size:20px; } #search-nav-form { padding: 4px 0 4px 0; text-align:center; border-top: 1px solid #abc; border-bottom: 1px solid #abc; } .search-nav { border: 3px double #999; border-left-color: #ccc; border-top-color: #ccc; color: #333; padding: 0.25em; } .search-nav-current { background-color: #acb; border: 3px double #999; border-left-color: #ccc; border-top-color: #ccc; color: #333; padding: 0.25em; } </style> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 | <?php // -------------------------------------------------------------------------------- // --- prepare results // -------------------------------------------------------------------------------- function prepare_results($search_results) { global $db, $q, $s_array, $searchterm, $exact_term, $exact_term_array; if ($search_results) { foreach ($search_results as $search_result) { $relevancy = 0; $match = 0; $context = ""; $word_array_keys = array(); $content = strtolower(strip_tags($search_result->content)); $lowertitle = strtolower(strip_tags($search_result->title)); $word_array = preg_split("/[\s,\.\"]+/",$content); for ($d=0; $d<=count($s_array); $d++) { if ($d==count($s_array)) { $searchterm = strtolower($q['s']); $first_word = $exact_term_array[0]; $match += 2*substr_count($content, $searchterm); // --- let's give bonus if full term matches $match += 4*substr_count($lowertitle, $searchterm); // --- let's give more bonus if full-term title matches... } else { $match += substr_count($content, $searchterm); $match += 2*substr_count($lowertitle, $searchterm); // --- let's give bonus if title matches... $searchterm = strtolower(strip_tags($s_array[$d])); } // -------------------------------------------------------------------------------- // --- bold any title words that match our search terms. // -------------------------------------------------------------------------------- $search_result->title = str_replace(ucfirst($searchterm),"<strong>".ucfirst($searchterm)."</strong>",$search_result->title); $search_result->title = str_replace(strtolower($searchterm),"<strong>".$searchterm."</strong>",$search_result->title); // -------------------------------------------------------------------------------- // --- bold the search words & prepare for getting some context snippets... // --- note that for exact search we'll just look at first word of phrase... // -------------------------------------------------------------------------------- if ($exact_term) { $temp_keys = array(); $found_keys = array(); $checking_keys = array(); $first_word_keys = array_keys($word_array, $first_word); // --- need to include as keys only if successive words match exact term since we // --- are starting with nly first word... foreach ($first_word_keys as $initial_key) { $term_match = true; $checking_keys[] = $initial_key; for ($x=1; $x<count($exact_term_array); $x++) { if ($word_array[$initial_key+$x]==$exact_term_array[$x]) { $checking_keys[] = $initial_key+$x; } else { $term_match = false; $checking_keys = array(); } } if ($term_match) array_push($found_keys,$checking_keys); } for ($y=0; $y<count($found_keys); $y++) { foreach ($found_keys[$y] as $key) { $temp_keys[] = $key; } } //print_r($temp_keys); echo "<hr>"; } else { $temp_keys = array_keys($word_array, $searchterm); } if (count($temp_keys)>0) { foreach ($temp_keys as $key) { $word_array_keys[] = $key; $word_array[$key] = "<strong>".$word_array[$key]."</strong>"; } } // -------------------------------------------------------------------------------- } $relevancy = $match; // -------------------------------------------------------------------------------- // --- let's get some context snippets... // -------------------------------------------------------------------------------- $buffer = 5; $i = 0; $range = array(); if (count($word_array_keys>0)) { asort($word_array_keys); //print_r($word_array_keys); echo "<hr>"; foreach ($word_array_keys as $n=>$key) { $range_start = $key-$buffer; if ($range_start<0) $range_start=0; $range_stop = $key + $buffer; if ($n==0) { $range[$i] = array($range_start,$range_stop); $i++; } else { if ($key-$buffer>$range[$i-1][1]) { $range[$i] = array($range_start,$range_stop); $i++; } } } } foreach ($range as $start_stop) { for ($e=$start_stop[0]; $e<=$start_stop[1]; $e++) { $context .= $word_array[$e]." "; } if ($word_array[$e]) $context = substr($context,0,strlen($context)-1)."... "; } // -------------------------------------------------------------------------------- // --- now let's store everything we found/created in an array... // -------------------------------------------------------------------------------- $results_array[] = array("ID"=>$search_result->ID,"title"=>$search_result->title,"content"=>$context,"modified"=>$search_result->modified,"relevancy"=>$relevancy); } } return($results_array); } // -------------------------------------------------------------------------------- // --- display_results // -------------------------------------------------------------------------------- function display_results($search_results) { global $searchterm; $numperpage = $_POST["show"]; $sort = $_POST["sort"]; $include = $_POST["include"]; $pagenumber = $_POST["pagenumber"]; //echo "results array"; print_r($search_results); echo "<br /><br />"; // -------------------------------------------------------------------------------- // --- sort and display search results... // -------------------------------------------------------------------------------- if (count($search_results)>0) { $entry = "Entries"; $count = count($search_results); $numpages = ceil($count/($numperpage)); $thispage = 1; if ($pagenumber) $thispage = $pagenumber; if ($_POST["next"]) $thispage = $_POST["lastpage"]+1; if ($_POST["prev"]) $thispage = $_POST["lastpage"]-1; if ($count==1) $entry = "Entry"; // --- decide whether to show all on one page or have multi-page results (count>$numperpage)... $start = 1; if ($thispage>1) $start = $numperpage*($thispage-1)+1; $limit = $count; if ($count>$numperpage) $limit = $numperpage; if ($thispage>1) $limit = $start+$numperpage-1; if ($thispage==$numpages) $limit = $count; // --- only show to last entry if on last page... //echo "start - " . $start . "; limit - " . $limit; // -------------------------------------------------------------------------------- // --- sort the results array // -------------------------------------------------------------------------------- foreach ($search_results as $key => $row) { $ID[$key] = $row['ID']; $chapter[$key] = $row['chapter']; $result_title[$key] = $row['title']; $modified_date[$key] = $row['modified']; $relevancy[$key] = $row['relevancy']; } if ($sort=="modified") array_multisort($modified_date, SORT_DESC, $search_results); if ($sort=="title") array_multisort($result_title, SORT_ASC, $search_results); if ($sort=="relevancy") array_multisort($relevancy, SORT_DESC, $search_results); //print_r($search_results); // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // --- display the results... // -------------------------------------------------------------------------------- echo "<h2>Search Results for <span style=\"border-bottom:1px dotted #999; color:green\">" . $searchterm . "</span>: <span style=\"\">" . $count . "</span> $entry Found (Displaying $start to $limit)</h1>\n"; echo "<ol start=\"".$start."\">\n"; for ($i=$start-1; $i<$limit; $i++) { echo "<li><a href=\"/content/".$search_results[$i][ID]."/\">" . $search_results[$i][title] . "</a> (". $search_results[$i][relevancy] . ")<br />" . $search_results[$i][content] . "<br /><br /></li>\n"; } echo "</ol>\n"; // -------------------------------------------------------------------------------- // --- now display the multi-page navigation... // -------------------------------------------------------------------------------- if ($count>$numperpage) { printf("<form method=\"post\" action=\"/search/\" id=\"search-nav-form\">\n"); if ($thispage>1) printf("<input type=\"submit\" name=\"prev\" value=\"<-- Prev\" class=\"search-nav\" />\n"); for ($n=1; $n<=$numpages; $n++) { if ($n==$thispage) { printf("<input type=\"submit\" name=\"pagenumber\" value=\"$n\" class=\"search-nav-current\" />\n"); } else { printf("<input type=\"submit\" name=\"pagenumber\" value=\"$n\" class=\"search-nav\" />\n"); } } if ($thispage<$numpages) printf("<input type=\"submit\" name=\"next\" value=\"Next -->\" class=\"search-nav\" />\n"); printf("<input type=\"hidden\" name=\"lastpage\" value=\"$thispage\" />\n"); printf("<input type=\"hidden\" name=\"search\" value=\"$searchterm\" />\n"); printf("<input type=\"hidden\" name=\"sort\" value=\"$sort\" />\n"); printf("<input type=\"hidden\" name=\"show\" value=\"$numperpage\" />\n"); printf("<input type=\"hidden\" name=\"include\" value=\"$include\" />\n"); foreach($search_results as $index => $ID) { printf("<input type=\"hidden\" name=\"search_results[$index]\" value=\"$search_results[$index]\" />\n"); } printf("</form>\n"); } } else { echo "<h2>No search results found for <span style=\"border-bottom:1px dotted #999; color:green\">" . $searchterm . "</span></h2>\n"; } } // -------------------------------------------------------------------------------- // --- show advanced search box... // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // --- massage search term & decide if searching for exact term or a boolean AND... // -------------------------------------------------------------------------------- $q['s'] = stripslashes(trim($_POST['search'])); if ( (substr($q['s'],0,1)=='"' AND substr($q['s'],-1)=='"') OR (substr($q['s'],0,1)=='"' AND substr($q['s'],-1)=='"') OR (substr($q['s'],0,1)=="'" AND substr($q['s'],-1)=="'") ) { $exact_term = true; $q['s'] = substr($q['s'],1,strlen($q['s'])-2); $s_array[] = $q['s']; $exact_term_array = explode(' ',$q['s']); } $n = '%'; // --- modify or remove special characters... $q['s'] = preg_replace('/, +/', ' ', $q['s']); $q['s'] = str_replace(',', ' ', $q['s']); $q['s'] = str_replace("+", "\+", $q['s']); $q['s'] = str_replace("$", "\$", $q['s']); $q['s'] = str_replace("?", "\?", $q['s']); $q['s'] = str_replace("^", "\^", $q['s']); $q['s'] = str_replace("*", " ", $q['s']); $q['s'] = str_replace("=", " ", $q['s']); $q['s'] = addslashes($q['s']); if (!$exact_term) $s_array = explode(' ',$q['s']); //echo "q is " . $q['s'] . "s_array is " . $s_array . "<br />"; // -------------------------------------------------------------------------------- // --- make sure at least one advanced search option and a sort is selected // -------------------------------------------------------------------------------- if (!$_POST["searchtitle"] && !$_POST["searchcontent"]) { $_POST["searchtitle"]=1; $_POST["searchcontent"]=1; } if (!$_POST["include"] && !$exact_term) $_POST["include"]=1; if ($exact_term) $_POST["include"]=3; if (!$_POST["sort"]) $_POST["sort"]="relevancy"; if (!$_POST["show"]) $_POST["show"]="50"; // -------------------------------------------------------------------------------- // --- add back quotes if exact search was requested // -------------------------------------------------------------------------------- $searchterm = stripslashes($q['s']); if ($exact_term) $searchterm = """.$searchterm."""; // -------------------------------------------------------------------------------- // --- configure all the advanced form fields for defaults... // -------------------------------------------------------------------------------- if ($_POST["include"]==1) $allselected = "checked=\"checked\""; if ($_POST["include"]==2) $anyselected = "checked=\"checked\""; if ($_POST["include"]==3) $exactselected = "checked=\"checked\""; if ($_POST["searchtitle"]==1) $titlechecked = "checked=\"checked\""; if ($_POST["searchcontent"]==1) $contentchecked = "checked=\"checked\""; if ($_POST["sort"]=="modified") $dateselected = "selected=\"selected\""; if ($_POST["sort"]=="title") $titleselected = "selected=\"selected\""; if ($_POST["sort"]=="relevancy") $relselected = "selected=\"selected\""; // -------------------------------------------------------------------------------- // --- now render the form... // -------------------------------------------------------------------------------- echo "<br />"; echo "<div id=\"searchform-advanced\">\n"; echo "<form id=\"searchform-advanced\" method=\"post\" action=\"/search/\">\n"; echo "<h1 style=\"\">Advanced Search</h1>\n"; echo "<strong>Search for: </strong>\n"; echo "<input maxlength=\"200\" name=\"search\" id=\"s\" value=\"".$searchterm."\" size=\"32\" type=\"text\" /> \n"; //echo "<a href=\"javascript:OpenWin('/includes/search-tips.inc.php', 300, 400);\"><strong>Advanced Search Tips</strong> ›</a>\n"; echo " <strong>Include:</strong>\n"; echo "<input type=\"radio\" name=\"include\" value=\"1\" $allselected />All\n"; echo "<input type=\"radio\" name=\"include\" value=\"2\" $anyselected />Any\n"; echo "<input type=\"radio\" name=\"include\" value=\"3\" $exactselected />Exact Phrase\n"; echo "<br />"; echo "<div style=\"margin-top:5px;\">\n"; echo "<strong>Appearing in:</strong>\n"; echo "<input type=\"checkbox\" name=\"searchtitle\" value=\"1\" $titlechecked />Title\n"; echo "<input type=\"checkbox\" name=\"searchcontent\" value=\"1\" $contentchecked />Article Contents\n"; echo "</div>\n"; echo "<strong>Sort by:</strong>\n"; echo "<select name=\"sort\">\n"; echo "<option $relselected value=\"relevancy\">Relevancy</option>\n"; echo "<option $dateselected value=\"modified\">Date</option>\n"; echo "<option $titleselected value=\"title\">Title</option>\n"; echo "</select>\n"; echo "<strong>Display:</strong>\n"; echo "<select name=\"show\">\n"; for ($c=1; $c<=10; $c++) { $num = $c*10; if ($_POST["show"]==$num) { $selected = "selected=\"selected\""; } else { $selected = ""; } echo "<option $selected value=\"$num\">$num/page</option>\n"; } echo "</select>\n"; echo "<input value=\"Search\" type=\"submit\" name=\"submit\" style=\"margin-top:5px;\" />\n"; echo "</form>\n"; echo "</div>"; // -------------------------------------------------------------------------------- // --- Perform search or display multiple page as appropriate... // -------------------------------------------------------------------------------- if ( !$_POST["search"] && ($_POST["pagenumber"] || $_POST["prev"] || $_POST["next"]) ) { display_results($_POST["search_results"]); } elseif ($_POST["search"]) { // -------------------------------------------------------------------------------- // --- generate sql to search the content table... // -------------------------------------------------------------------------------- $search_sql = ' SELECT * FROM content WHERE ( '; switch ($_POST["include"]) { case "1": // all terms $q['search_terms'] = $s_array; $search_sql .= '('; if ($_POST["searchtitle"]==1 || $_POST["searchcontent"]==1) { $search_sql .= '('; if ($_POST["searchtitle"]==1) $search_sql .= 'title LIKE \''.$n.$s_array[0].$n.'\''; if ($_POST["searchtitle"]==1 && $_POST["searchcontent"]==1) $search_sql .= ' OR'; if ($_POST["searchcontent"]==1) $search_sql .= ' content LIKE \''.$n.$s_array[0].$n.'\''; $search_sql .= ')'; for ( $i = 1; $i < count($s_array); $i = $i + 1) { $search_sql .= ' AND ('; if ($_POST["searchtitle"]==1) $search_sql .= 'title LIKE \''.$n.$s_array[$i].$n.'\''; if ($_POST["searchtitle"]==1 && $_POST["searchcontent"]==1) $search_sql .= ' OR'; if ($_POST["searchcontent"]==1) $search_sql .= ' content LIKE \''.$n.$s_array[$i].$n.'\''; $search_sql .= ')'; } $search_sql .= ')'; if (count($s_array)>1) { if ($_POST["searchtitle"]==1) $search_sql .= ' OR (title LIKE \''.$n.$q['s'].$n.'\') '; if ($_POST["searchcontent"]==1) $search_sql .= ' OR (content LIKE \''.$n.$q['s'].$n.'\')'; } } break; case "2": // any term $q['search_terms'] = $s_array; $search_sql .= '('; if ($_POST["searchtitle"]==1 || $_POST["searchcontent"]==1) { $search_sql .= '('; if ($_POST["searchtitle"]==1) $search_sql .= 'title LIKE \''.$n.$s_array[0].$n.'\''; if ($_POST["searchtitle"]==1 && $_POST["searchcontent"]==1) $search_sql .= ' OR'; if ($_POST["searchcontent"]==1) $search_sql .= ' content LIKE \''.$n.$s_array[0].$n.'\''; $search_sql .= ')'; for ( $i = 1; $i < count($s_array); $i = $i + 1) { $search_sql .= ' OR ('; if ($_POST["searchtitle"]==1) $search_sql .= 'title LIKE \''.$n.$s_array[$i].$n.'\''; if ($_POST["searchtitle"]==1 && $_POST["searchcontent"]==1) $search_sql .= ' OR'; if ($_POST["searchcontent"]==1) $search_sql .= ' content LIKE \''.$n.$s_array[$i].$n.'\''; $search_sql .= ')'; } $search_sql .= ')'; } break; case "3": // exact term if ($_POST["searchtitle"]==1) $search_sql .= ' title LIKE \''.$n.$q['s'].$n.'\' '; if ($_POST["searchcontent"]==1) $search_sql .= ' OR content LIKE \''.$n.$q['s'].$n.'\' '; break; } $search_sql .= ' )'; //echo "search sql is " . $search_sql . "<br />"; // -------------------------------------------------------------------------------- // --- now do the actual content search... // -------------------------------------------------------------------------------- if ($_POST["searchtitle"] || $_POST["searchcontent"]) $search_results = $db->get_results($search_sql); // -------------------------------------------------------------------------------- // --- now prepare the results (assign relevancy AND select context text)... // -------------------------------------------------------------------------------- $results_array = prepare_results($search_results); // -------------------------------------------------------------------------------- // --- finally, display the results... // -------------------------------------------------------------------------------- display_results($results_array); } ?> |
It is written to search a table called content with the two primary fields to search being title and content. Other relevant fields are ID and modified. Please note that, as with so many coding exercises, I put this together in pieces over time. As a result, I am sure there are many pieces of inefficient code. If you improve any of these, please let me know and I will update the script and provide appropriate acknowledgement.
As you can see, there are several main sections of code. Below I offer an overview of what each does.
prepare_results: this function takes the initial search results and assigns relevancy to each, highlights the search term(s), and selects context text. The relevancy algorithm is completely pulled from thin air on my part. My thinking is that I want an exact phrase match to have higher relevancy. I also want a match found in the title to have higher relevancy, all things equal, than a match in the content. You can pretty easily modify this algorithm to suit your needs. To get the context I break up all the content into words and assign them to an array. This allows for the context to contain only full words. You could simplify this greatly by just choosing a certain number of character before and after the found search term(s). Either way, the tricky thing to worry about it when you have multiple occurrences of a search term. If the occurrences are close in proximity, you could end up displaying the same partial text multiple times. My code corrects for this.
display_results: this function takes the final search results, sorts them and then displays an ordered list of the results. If appropriate, it creates a multi-page navigation at the bottom of the page and stores the search results (as well as the advanced search form options) in hidden variables to aid the functionality on the subsequent pages.
show advanced search box: this section of code displays the advanced search form, sets default option values if appropriate and also modifies the search term to remove any special characters which can be trouble for our database query.
Perform search or display multiple page as appropriate: this section of code performs the search if the search form was just submitted, but if we are using the multi-page results navigation there is no need to perform the search again as we store the results; we can just jump to the display_results section.
generate sql: this code uses the MySQL LIKE statement to do the searches. I have tried to use a text matching algorithm that loops through all table rows but have found that when the table size grows it becomes quite slow, especially since we are creating context display text, testing Boolean expressions, etc. The sql generated accounts for the Boolean or exact phrase nature of the search.
Finally, if you would rather not bother with implementing your own search feature, you might want to try a third party script. I haven’t used it myself, but I have heard that Sphider is a good option. It is a lightweight web spider and search engine written in PHP, using MySQL as its back end database. It is small, easy to set up and modify, and is used in thousands of websites across the world.
Click to Add the First »
