写了个查找字符串中的关键词,将其高亮,不知道有没有什么问题。
protected function madeHighlight( $data )
{
//多个关键词以空格隔开
$keywords = explode(' ', $_REQUEST[ 'q' ]);
foreach ( $data as &$str ) {
foreach ( $keywords as $word ) {
//关键词长度
$wordLength = mb_strlen($word);
$start = -1;
//查找字符串中的所有出现关键词的位置
while ( ( $pos = mb_strpos(strtolower($str[ 'title' ]), strtolower($word), $start + 1) ) !== false ) {
$hightLight = 'aa-' . mb_substr($str[ 'title' ], $pos, $wordLength) . '-aa';
//加上高亮代码之后的字符串
$newStr = mb_substr($str[ 'title' ], 0, $pos) . $hightLight . mb_substr($str[ 'title' ], $pos + $wordLength);
$str[ 'title' ] = $newStr ;
//从高亮的关键词之后继续查找关键词
$start = $pos + mb_strlen($hightLight);
}
}
}
return $data;
}