I made a small web application with a search box. I wanted to highlight the words found in the search.
foreach my $article (@{$search_articles}) {
my @result;
foreach my $word (split(' ', $article->{content})) {
if ( $word =~ params->{search} ) {
push(@result,
'<span style="background: yellow">' . $word . '</span>');
}
else {
push(@result, $word);
}
}
$article->{content} = join(' ', @result);
}
It's a little wordy. It is certainly possible to make cleaner, and I'd like to have your opinion.
1 Answer 1
Assuming that your search input is plain characters (i.e., no <
, >
, and likes), this is still problematic as can ruin your HTML code. Let's say I search for "border" in a page that contains <table border="1">
, or "class" in virtually any page written in the past 5 years,... IMO, this stuff is better done using a DOM parser and then searching just plain text.
Now, to comment the search itself... Let us assume that the word from your search box is contained in the variable $search
. I think this is better done like this:
foreach my $article (@{$search_articles}) {
$article->{content} =~ s/\Q$word\E/<span style="background: yellow">$&<\/span>/g
}