【发布时间】:2015-12-03 20:40:18
【问题描述】:
我在网站上显示搜索结果,用户可以在其中搜索特定关键字、词。
在结果页面上,我试图在结果中突出显示搜索的单词。 所以用户可以知道哪些词在哪里匹配。
例如
if user searches for : mango
the resulting item original : This Post contains Mango.
the resulting output I want of highlighted item : This Post contains <strong>Mango</strong>
我就是这样用的。
<?php
//highlight all words
function highlight_words( $title, $searched_words_array) {
// loop through searched_words_array
foreach( $searched_words_array as $searched_word ) {
$title = highlight_word( $title, $searched_word); // highlight word
}
return $title; // return highlighted data
}
//highlight single word with color
function highlight_word( $title, $searched_word) {
$replace = '<strong>' . $searched_word . '</strong>'; // create replacement
$title = str_ireplace( $searched_word, $replace, $title ); // replace content
return $title; // return highlighted data
}
我正在从 Sphinx Search Engine 获取搜索词,问题是 Sphinx 以小写形式返回输入/macthed 词。
所以通过使用上面的代码,我的
results becomes : This Post contains <strong>mango</strong>
*注意 mango 中的 m 是小写的。
所以我的问题是如何突出显示单词,即将<strong> 和</strong> 包裹在与搜索单词匹配的单词周围?
不丢失它的文本框?
*pp。它与how to highlight search results 的问题不同,我问我的关键字数组是小写的,并使用上述方法将原始单词替换为小写单词。
那么我该如何阻止呢?
其他问题链接也会面临这个问题,因为搜索到的关键字都是小写的。并使用str_ireplace 将匹配它并用小写单词替换它。
更新:
我结合了各种代码 sn-ps 来得到我期望代码做的事情。, 现在它工作得很好。
function strong_words( $title, $searched_words_array) {
//for all words in array
foreach ($searched_words_array as $word){
$lastPos = 0;
$positions = array();
//find all positions of word
while (($lastPos = stripos($title, $word, $lastPos))!== false) {
$positions[] = $lastPos;
$lastPos = $lastPos + strlen($word);
}
//reverse sort numeric array
rsort($positions);
// highlight all occurances
foreach ($positions as $pos) {
$title = strong_word($title , $word, $pos);
}
}
//apply strong html code to occurances
$title = str_replace('#####','</strong>',$title);
$title = str_replace('*****','<strong>',$title);
return $title; // return highlighted data
}
function strong_word($title , $word, $pos){
//ugly hack to not use <strong> , </strong> here directly, as it can get replaced if searched word contains charcters from strong
$title = substr_replace($title, '#####', $pos+strlen($word) , 0) ;
$title = substr_replace($title, '*****', $pos , 0) ;
return $title;
}
$title = 'This is Great Mango00lk mango';
$words = array('man','a' , 'go','is','g', 'strong') ;
echo strong_words($title,$words);
【问题讨论】:
-
@bub 的主要功能是从那个链接修改的,因为我只是想使用单色,它不是同一个问题。
标签: php str-replace highlighting