1
\$\begingroup\$

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.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Sep 10, 2013 at 19:13
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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
}
answered Sep 10, 2013 at 20:05
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.