[英]Highlight multiple keywords advanced
我嘗試了此處回答的大多數解決方案,但所有解決方案都存在相同的問題,這是我在這里提出的問題。
我將此功能用於高亮度搜索結果:
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 =“我具有最高系統性能”和searchstrings =“ max f”
在第一次迭代中,foreach將用<font color='#00f'><b>max</b></font>
替換每個最大值
在第二次迭代中,它將用<font color='#00f'><b>f</b></font>
替換每個f
第二次迭代也將替換第一次替換中插入的html標簽! 因此,它也將替換字符串<font color='#00f'>
f嗎?
有什么建議嗎? 謝謝Miodrag
<?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));
?>
嘗試以下
foreach ( $words as $word ){
if(strlen ($word)>2)
{
$highlighted[] = "<font color='#00f'><b>".$word."</b></font>";
}
}
也許這對您來說是一個很好的解決方案?
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 ormance Max系統
更新:如果您想突出顯示完整的單詞,請查看以下內容:
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.