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

commented: very helpful +0

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!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.