Return to Snippet

Revision: 68997
at April 2, 2015 02:41 by flatearthcomms


Initial Code
/**
 * 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
 */
function array_find($needle, array $haystack)
{
    foreach ($haystack as $key => $value) {
        if (false !== stripos($needle, $value)) {
            return $key;
            //break;
        }
    }
    return false;
}

/* Rest of code Flat Earth */

$search = strtoupper($search); 
$search = strip_tags($search); 
$search = trim($search); 

$sql_srch = "SELECT * FROM `pg_pages` WHERE upper(`story`) LIKE'%$search%'"; 
$result_srch = doSQL($sql_srch);
$c_srch=mysql_num_rows($result_srch);
for($i_srch=0; $i_srch<$c_srch; $i_srch++) 
{ 
	$r_srch = mysql_fetch_array( $result_srch );
	$srchUrl = $r_srch['tier1'].$r_srch['tier2'].$r_srch['tier3'] ;
	echo '<a href="'.$srchUrl.'">'.$r_srch['title'].'</a>';

	$stry = $r_srch['story'];
	$stry = ereg_replace ( "<h1>(.*)</h1>", "", $stry );
	$stry = strip_tags($stry);
	
	$stryArray = explode(" ", $stry);
	$foundPosition = FALSE;
	$foundPosition = array_search( strtolower($search), array_map('strtolower',$stryArray) );
	// * 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)?'':'...';
	$endPosition = ($foundPosition+1+$extractWords < count($stryArray) )?$extractWords:count($stryArray)-$foundPosition;
	$endEllipsis = (count($stryArray)-$foundPosition<=$extractWords)?'':'...';
	
	$stryStart = implode(' ', array_slice($stryArray, $foundPosition-$startPosition, $startPosition) );
	$stryEnd = implode(' ', array_slice($stryArray, $foundPosition+1, $endPosition) );
	//$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&rsquo;t find anything that matches your search criteria.</p>"; 
}

Initial URL


Initial Description
Simple PHP search with whole word extract and highlighted search word

Initial Title
Simple PHP search with whole word extract and highlighted search word

Initial Tags
search

Initial Language
PHP