Use $&
, which will be set to the matched string:
my $text = "Albert Hammond's guitar from Gibraltar.";
foreach my $text ('guitar', 'Gibraltar') {
my $replace = "<span style='color:white;background-color:red'>" . $& . "</span>";
$text =~ s/$search/$replace/gi;
}
Update: this won't work, as @ThisSuitIsBlackNot comments below: the $&
will not be interpreted in the replacement string when that string is a variable. (I didn't know this.) So you have to get rid of the variable:
my $text = "Albert Hammond's guitar from Gibraltar.";
foreach my $search ('guitar', 'Gibraltar') {
my $replace = "";
$text =~ s/$search/<span style='color:white;background-color:red>$&<\/span>/gi;
}
This prints
Albert Hammond's <span style='color:white;background-color:red>guitar</span> from <span style='color:white;background-color:red>Gibraltar</span>.
Note that I also had to escape the /
in the replacement string because /
is also used to delimit the arguments of the s
command.
This may still not be good enough.
It assumes your values for $search
will never contain any characters that are special to regular expressions (such as .
or *
).
If they might, you can escape them using qr
.
It also assumes those values never contain any characters special to XML (such as <
or >
, or the '
in my example.). If they might, use an XML manipulation library such as XML::LibXML to make the changes, or use XSLT.