1
A
回答
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>?)。
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);
}
就像一個魅力!
相關問題
- 1. php如何在mysql中搜索關鍵字
- 2. MySQL搜索關鍵字
- 3. mysql關鍵字搜索
- 4. MySQL關鍵字搜索?
- 5. 關鍵字PHP搜索
- 6. PHP MYSQL在多個表中搜索相同的關鍵字
- 7. 搜索php + mysql的關鍵詞?
- 8. 在PHP/MySql中使用多個關鍵字進行搜索
- 9. PHP在mysql中搜索多個關鍵字
- 10. 跨多列的mysql關鍵字搜索
- 11. MySQL的sqlalchmey關鍵字搜索
- 12. 如何在PHP中通過關鍵字搜索Json?
- 13. 用php和mysql搜索多個關鍵字(其中X就像)
- 14. 如何在搜索中添加其他關鍵字?
- 15. Mysql全文搜索 - 搜索關鍵字的一部分
- 16. 帶有多個關鍵字的PHP/MySQL複雜搜索
- 17. PHP,通過關鍵字搜索的MySQL從多個表
- 18. 多個關鍵字搜索使用PHP MySQL的結果記錄
- 19. 搜索多個表使用關鍵字PHP的MySQL
- 20. PHP使用關鍵字的MYSQL搜索引擎
- 21. 在DNN中的關鍵字搜索
- 22. 谷歌搜索客戶輸入關鍵字在PHP
- 23. 使用PHP執行關鍵字搜索
- 24. php關鍵字搜索不起作用
- 25. MySQL:在評論字符串中搜索關鍵字
- 26. 論壇搜索引擎在php中搜索數據庫中的關鍵字
- 27. 搜索SP的關鍵字
- 28. 「加」關鍵字不工作MySQL的全文搜索
- 29. 插入並搜索多個關鍵字
- 30. 幫助!關鍵字在MySql全文搜索中的優先級!
他將有多個單詞,所以'preg_replace'和一組模式將是一個更合適的解決方案。 – Keyo 2010-10-12 03:37:19
這不考慮字符大小寫。如果'你好'是你的搜索詞,'你好'不會被包裹在b標籤中。 – joshmmo 2014-02-26 17:48:50
str_ireplace將解決這個問題 – joshmmo 2014-02-26 18:04:28