Home  >  Article  >  Backend Development  >  How to highlight keywords in site search results?

How to highlight keywords in site search results?

WBOY
WBOYOriginal
2016-10-10 11:56:09905browse

How to highlight keywords in the returned results when searching within the site?

Reply content:

How to highlight keywords in the returned results when searching within the site?

You can use pair replacementfunction strtr:
string strtr ( string $str , array $replace_pairs )

<code><?php
header('Content-Type: text/plain; charset=utf-8');
$arr = array('中国', '中国人'); //关键字
foreach($arr as $v) { $new[$v] = '<b>'.$v.'</b>'; }
var_export($new); //输出: array( '中国' => '<b>中国</b>', '中国人' => '<b>中国人</b>' )
$str = '我是中国人我爱中国';
echo strtr($str, $new)."\n"; //输出: 我是<b>中国人</b>我爱<b>中国</b>

//对比:str_replace会发生重复替换,下面代码会输出: 我是<b><b>中国</b>人</b>我爱<b>中国</b>
echo str_replace(array('中国人','中国'), array('<b>中国人</b>','<b>中国</b>'), '我是中国人我爱中国');</code>

It is recommended to use elasticsearch. This is a search engine written in java and based on lunce

<code><?php
$str = "Hello world!";
$keyword = "world";
echo str_replace($keyword, "<font color='red'>" . $keyword . "</font>", $str);
?></code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn