I want to search "The tree is in the yard" for the word "the", then replace the word "the" with "<font color=#FFFFFF>the</font>", which I currently do with "s/$searchstring/<font color=#FFFFFF>$searchstring</font>/gi;" BUT I want to preserve the case of the word, so that in this example the first word of the sentence would be white, but would have the capital T preserved. How can I do this?


Thanks,
Derek

What you need to use is one of the back-reference variables, specifically you should use "$&" since you essentially want to reuse each occurrence of your search string

Give this a try

$someText =~ s/$searchstring/<font color=#FFFFFF>$&<\/font>/gi;

I want to search "The tree is in the yard" for the word "the", then replace the word "the" with "<font color=#FFFFFF>the</font>", which I currently do with "s/$searchstring/<font color=#FFFFFF>$searchstring</font>/gi;" BUT I want to preserve the case of the word, so that in this example the first word of the sentence would be white, but would have the capital T preserved. How can I do this?


Thanks,
Derek

Comments
very helpful

What you need to use is one of the back-reference variables, specifically you should use "$&" since you essentially want to reuse each occurrence of your search string

Give this a try

$someText =~ s/$searchstring/<font color=#FFFFFF>$&<\/font>/gi;

wow! So simple! This worked PERFECTLY! Thanks a million!

This question has already been answered. Start a new discussion instead.