PHP 简单的PHP搜索,包括全字提取和突出显示的搜索词

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP 简单的PHP搜索,包括全字提取和突出显示的搜索词相关的知识,希望对你有一定的参考价值。

/**
 * 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 <branmovic@gmail.com>
 * @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’t find anything that matches your search criteria.</p>"; 
}

以上是关于PHP 简单的PHP搜索,包括全字提取和突出显示的搜索词的主要内容,如果未能解决你的问题,请参考以下文章

PHP PHP包括导航,选择/突出显示当前页面

PHP 搜索词突出显示

PHP/MySQL:突出显示“SOUNDS LIKE”查询结果

php 简单语法突出显示

如何从 PDF 文件中提取突出显示的部分

php - preg_replace 突出显示格式化的电话号码