Given 1) a scalar containing search terms separated by spaces, 2) a scalar block of text that might contain the terms, and 3) a scalar hex color like #FF0000, this sub will return the block of text with each term highlighted (in HTML, using the bold tag with an inline style) with the color. This sub makes no attempt to escape regex control characters -- have fun. And yes, I'm fully prepared to be informed that this functionality has been available in some widespread module for years...
sub HTMLhighlight { my($searchterms,$instr,$color) = @_; my (@terms)=split(/\ /,$searchterms); foreach $i (0..$#terms) { $instr =~ s/(?!<.*)($terms[$i])(?!.*>)/<b style=\"background:$colo +r\">$1<\/b>/gi; } return $instr; }

Replies are listed 'Best First'.
RE: HTMLHighlight
by AltBlue (Chaplain) on Sep 13, 2000 at 13:35 UTC
    are you sure about that? at 1st sight seems that you're using lookbehind assertion inccorectly... so i run a test code over you function:
    #!/usr/bin/perl -w use strict; my $terms = 'tree crow black blue green stars'; my $color = '#CC0000'; my $string1= qq!\tthe black crow is sitting in the <font color="blue"> +tree</font> looking at the green stars!; my $string2= qq!\tthe black crow is sitting in the blue tree looking a +t the green stars!; print 'Terms: '.$terms.$/x2; print 'text1:'.$/.$string1.$/; print 'parsed1:'.$/.HTMLhighlight($terms,$string1,$color).$/; print 'text2:'.$/.$string2.$/; print 'parsed2:'.$/.HTMLhighlight($terms,$string2,$color).$/; sub HTMLhighlight { my($searchterms,$instr,$color) = @_; my (@terms)=split(/\ /,$searchterms); foreach my $i (0..$#terms) { $instr =~ s/(?!<.*)($terms[$i])(?!.*>)/<b style=\"background:$colo +r\">$1<\/b>/gi; } return $instr; } # a easier way to do the same thing =] sub HTMLhighlight2 { my ($searchterms,$instr,$color) = @_; $searchterms =~ s/\s+/|/g; $instr =~ s#($searchterms)#<b style="background:$color">$1</b>#gi; return $instr; }

    the output is something like this (hope that *code* will keep html tags parsing off :)) ):

    Terms: tree crow black blue green stars text1: the black crow is sitting in the <font color="blue">tree</font> lo +oking at the green stars parsed1: the black crow is sitting in the <font color="blue">tree</font> lo +oking at the <b style="background:#CC0000">green</b> <b style="backgr +ound:#CC0000">stars</b> text2: the black crow is sitting in the blue tree looking at the green st +ars parsed2: the black crow is sitting in the blue <b style="background:#CC0000 +">tree</b> looking at the <b style="background:#CC0000">green</b> <b +style="background:#CC0000">stars</b>

    not so good.. i don't have yet an elegant solution for exempting searchterms to be parsed when inside html code but still provided you the htmlhighlight2 .. that look a little bit more efficient ;-] (ofc, skipped the futile lookbehind assertions)

    --
    AltBlue.