/ Perl

Search Keyword Highlighting with Perl

Here's how to break down a search string into uniq keywords and highlight them using HTML:

# user input
my $search_string = "I really really need this";

# highlighting, get the s _uniq_ keyword
# use grep() to make sure we skip short keywords
my @kw = grep {length($_) > 2} split /[^w]/,$search_string;

# expected output: keyword1|keyword2|keyword3
my $regex_keys = join "|", sort keys %{{ map { $_ => 1 } @kw }};

$data =~ s!($regex_keys)!<span class="kw">1</span>!ig;

print $data;

Here, $data is a hash of stuff from a database of some sort.

The interesting part is:

my $regex_keys = join "|", sort keys %{{ map { $_ => 1 } @kw }};

This line creates an anonymous hash with all the elements of the array as keys with a dummy 1 value. The keys sub in turn returns the keys and since map would've overwritten any duplicate keys, they are now unique!

Make sure that $regex_keys is sanitized before going to production with something like this.