2010-10-12 95 views

回答

3

只需在返回的文本上執行str_replace。

$search = 'programming'; 
// $dbContent = the response from the database 

$dbContent = str_replace($search , '<b>'.$search.'</b>' , $dbContent); 

echo $dbContent; 

「編程」的任何實例,即使作爲一個大單詞的一部分,將被包裹在<b>標籤。

對於實例,其中一個以上的字被用於

$search = 'programming something another'; 
// $dbContent = the response from the database 

$search = explode(' ' , $search); 
function wrapTag($inVal){ 
    return '<b>'.$inVal.'</b>'; 
} 
$replace = array_map('wrapTag' , $search); 

$dbContent = str_replace($search , $replace , $dbContent); 

echo $dbContent; 

這將$search分成在空間的陣列,然後包裹在<b>標記每個匹配。

您可以使用<b><strong>標籤(有關它們的討論,請參閱What's the difference between <b> and <strong>, <i> and <em>?)。

+0

他將有多個單詞,所以'preg_replace'和一組模式將是一個更合適的解決方案。 – Keyo 2010-10-12 03:37:19

+0

這不考慮字符大小寫。如果'你好'是你的搜索詞,'你好'不會被包裹在b標籤中。 – joshmmo 2014-02-26 17:48:50

+0

str_ireplace將解決這個問題 – joshmmo 2014-02-26 18:04:28

2
$search = @$_GET['q']; 
$trimmed = trim($search); 

function highlight($req_field, $trimmed) //$req_field is the field of your table 
{ 
     preg_match_all('~\w+~', $trimmed, $m); 
     if(!$m) 
      return $req_field; 
     $re = '~\\b(' . implode('|', $m[0]) . ')\\b~'; 
     return preg_replace($re, '<b>$0</b>', $req_field); 
} 

    print highlight($req_field, $trimmed); 

通過這種方式,你可以博爾登搜索關鍵字。它非常簡單並且運作良好。

0

答案實際上比這更復雜一點。在常見的搜索結果用例中,還有其他一些因素需要考慮:

  • 您應該考慮大寫和小寫(編程,編程,編程等);
  • 如果您的內容字符串非常長,您不希望返回整個文本,而只是搜索到的查詢以及其前後的幾個單詞,以獲取上下文;

This guy想通了:

//$h = text 
//$n = keywords to find separated by space 
//$w = words near keywords to keep 

function truncatePreserveWords ($h,$n,$w=5,$tag='b') { 
    $n = explode(" ",trim(strip_tags($n))); //needles words 
    $b = explode(" ",trim(strip_tags($h))); //haystack words 
    $c = array();      //array of words to keep/remove 
    for ($j=0;$j<count($b);$j++) $c[$j]=false; 
    for ($i=0;$i<count($b);$i++) 
     for ($k=0;$k<count($n);$k++) 
      if (stristr($b[$i],$n[$k])) { 
       $b[$i]=preg_replace("/".$n[$k]."/i","<$tag>\\0</$tag>",$b[$i]); 
       for ($j= max($i-$w , 0) ;$j<min($i+$w, count($b)); $j++) $c[$j]=true; 
      } 
    $o = ""; // reassembly words to keep 
    for ($j=0;$j<count($b);$j++) if ($c[$j]) $o.=" ".$b[$j]; else $o.="."; 
    return preg_replace("/\.{3,}/i","...",$o); 
} 

就像一個魅力!