Skip to content

Commit

Permalink
improve highlighting algorithm once more
Browse files Browse the repository at this point in the history
  • Loading branch information
David Grosse committed Jul 5, 2022
1 parent 30d00e3 commit b621af4
Showing 1 changed file with 20 additions and 7 deletions.
27 changes: 20 additions & 7 deletions src/Http/Livewire/Posts.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,16 +68,29 @@ private function highlightSearchResults(Collection $posts, ?string $search = nul
return $posts;
}

$class = config('zeus-sky.search_result_highlight_css_class', 'highlight');

foreach ($posts as $i => $post) {
$posts[$i]->content = str_ireplace(
$search,
sprintf('<span class="%s">%s</span>', $class, $search),
$post->content,
);
$posts[$i]->content = static::hl($post->content, [$search]);
}

return $posts;
}

/**
* Credits for this code goes to link below.
*
* @link https://stackoverflow.com/questions/8564578/php-search-text-highlight-function
*/
public static function hl(string $inp, array $words): string
{
$class = config('zeus-sky.search_result_highlight_css_class', 'highlight');
$replace = array_flip(array_flip($words));
$pattern = [];

foreach ($replace as $k => $fword) {
$pattern[] = '/\b('.$fword.')(?!>)\b/i';
$replace[$k] = sprintf('<span class="%s">$1</span>', $class);
}

return preg_replace($pattern, $replace, $inp);
}
}

0 comments on commit b621af4

Please sign in to comment.