/ Published in: PHP
Simple PHP search with whole word extract and highlighted search word
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/** * Case in-sensitive array_search() with partial matches * * @param string $needle The string to search for. * @param array $haystack The array to search in. * * @author Bran van der Meer <[email protected]> * @since 29-01-2010 */ { foreach ($haystack as $key => $value) { return $key; //break; } } return false; } /* Rest of code Flat Earth */ $sql_srch = "SELECT * FROM `pg_pages` WHERE upper(`story`) LIKE'%$search%'"; $result_srch = doSQL($sql_srch); for($i_srch=0; $i_srch<$c_srch; $i_srch++) { $srchUrl = $r_srch['tier1'].$r_srch['tier2'].$r_srch['tier3'] ; echo '<a href="'.$srchUrl.'">'.$r_srch['title'].'</a>'; $stry = $r_srch['story']; $foundPosition = FALSE; // * Rare instance where search for 'founded' finds 'co-founded' therefore isn't matched // * So search for fragment of search phrase // * WARNING: means 'found' is found first if it exists, but at least gives result if($foundPosition===FALSE) { $foundPosition = array_find( $search, $stryArray ); $stryWord = '<span class="notfound">' . implode(' ', array_slice($stryArray, $foundPosition, 1) ). '</span>'; } else { $stryWord = '<span class="found">' . implode(' ', array_slice($stryArray, $foundPosition, 1) ). '</span>'; } $extractWords = 11; $startPosition = ($foundPosition-$extractWords > 0)?$extractWords:$foundPosition; $startEllipsis = ($startPosition<$extractWords)?'':'...'; //$stryWord = '<span class="found">' . implode(' ', array_slice($stryArray, $foundPosition, 1) ). '</span>'; $fndstry = $startEllipsis. $stryStart .' '. $stryWord .' '. $stryEnd .$endEllipsis; echo "<p>".$fndstry."</p>"; } if ($c_srch == 0) { echo "<p>Sorry, but we can’t find anything that matches your search criteria.</p>"; }