我尝试了这里回答的大部分解决方案,但所有这些解决方案都有相同的问题,这是我在这里的问题。
我将此功能用于高级搜索结果:
function highlightWords($searchtext, $searchstrings){
$searchstrings = preg_replace('/'s+/', ' ', trim($searchstrings));
$words = explode(' ', $searchstrings);
$highlighted = array();
foreach ( $words as $word ){
$highlighted[] = "<font color='#00f'><b>".$word."</b></font>";
}
return str_replace($words, $highlighted, $searchtext);
}
当我搜索带有 2 个或更多用空格分隔的字符串的文本并且其中任何一个都有我突出显示的数组中的任何 HTML 代码时,就会出现问题。
例如,searchtext="I have max system performance" AND searchstrings="max f"
在第一次迭代中,foreach 将用 <font color='#00f'><b>max</b></font>
替换每个最大值
在第二次迭代中,它将用<font color='#00f'><b>f</b></font>
替换每个f。
第二次迭代也将替换第一次替换中插入的 html 标签!所以它也会替换字符串中的 f <font color='#00f'>
?
有什么建议吗?谢谢米奥德拉格
<?php
$searchtext = "I have max system performance";
$searchstrings = "max f";
$searchstrings = preg_replace('/'s+/', ' ', trim($searchstrings));
$words = explode(' ', $searchstrings);
$highlighted = array();
foreach ( $words as $word ){
$highlighted[] = "<font color='#00f'><b>".$word."</b></font>";
}
echo strtr($searchtext, array_combine($words, $highlighted));
?>
也许这对您来说是很好的解决方案?
function highlightWords($searchtext, $searchstrings){
$searchstrings = preg_replace('/'s+/', ' ', trim($searchstrings));
$words = explode(' ', $searchstrings);
$highlighted = array();
foreach ( $words as $word ){
$highlighted[] = '<span class="highlighted-word">'.$word.'</span>';
}
return str_replace($words, $highlighted, $searchtext);
}
echo highlightWords('I have max system performance', 'max f');
?>
您需要在主页上添加一些 CSS:
<style>
.highlighted-word {
font-weight: bold;
}
</style>
输出:我有每个f弹药的最大系统
---
更新:如果您想突出显示完整的单词,请查看以下内容:
function highlightCompleteWords($searchtext, $searchstrings){
$searchstrings = preg_replace('/'s+/', ' ', trim($searchstrings));
$words = explode(' ', $searchstrings);
$highlighted = array();
foreach ( $words as $word ){
$searchtext = preg_replace("/'w*?".preg_quote($word)."'w*/i", "<span class='highlighted-word'>$0</span>", $searchtext);
}
return $searchtext;
}
echo highlightCompleteWords('I have max system performance', 'max f');
输出:我有最大的系统性能
我可能不完全理解您的问题,但我想您想突出显示搜索字符串中的每个匹配单词。
您可能可以执行以下操作:
$returnString = $searchtext;
foreach ( $words as $word ){
$returnString = preg_replace('/'b'.$word.''b/i', "<font color='#00f'><b>$0</b></font>", $returnString);
}
return $returnString;
这将输出:"我有最大的系统性能"
由于"f"不匹配
编辑 - 这是如果您还想匹配单词的一部分。
有点丑,但我相信这会为你分叉
$returnString = $searchtext;
foreach ( $words as $word ){
if(strlen($word)>2){
$returnString = preg_replace('/'.$word.'/i', "§§§$0###", $returnString);
}
}
$returnString = preg_replace("/'§§§/","<font color='#00f'><b>", $returnString);
$returnString = preg_replace("/'###/","</b></font>", $returnString);
return $returnString;
尝试以下操作
foreach ( $words as $word ){
if(strlen ($word)>2)
{
$highlighted[] = "<font color='#00f'><b>".$word."</b></font>";
}
}