[solved]help with automated highlighting

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Black_cage85
Forum Newbie
Posts: 4
Joined: Wed Sep 06, 2006 6:11 am

[solved]help with automated highlighting

Post by Black_cage85 »

I have a variable which I load some text into. I would like it to highlight a specific word that the user supplies. I will give you and example.

Code: Select all

<?php

$contents = ""Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed turpis. In mattis aliquet felis. Nunc sagittis urna ac felis. Phasellus sed contribute velit. Donec orci sem, tempus pharetra, fermentum nec, pellentesque vitae, massa."

?>
I would like to automatically select out a would which is typed into an input box on the page before, so if the user input 'contribute' I would like the output to look like this:

Code: Select all

<?php

echo "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed turpis. In mattis aliquet felis. Nunc sagittis urna ac felis. Phasellus sed <span class=\"exactMatch\">contribute</span> velit. Donec orci sem, tempus pharetra, fermentum nec, pellentesque vitae, massa."
?>
Hope this is clear and any help would be greatly appreciated.
Last edited by Black_cage85 on Wed Sep 06, 2006 8:37 am, edited 1 time in total.
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post by CoderGoblin »

preg_replace may be of use. Simply replace the word with the tag+word+closetag. You can also use str_replace if not checking for complete words only.
Black_cage85
Forum Newbie
Posts: 4
Joined: Wed Sep 06, 2006 6:11 am

Post by Black_cage85 »

I used 'str_replace' and that did the trick, thanks for your help.
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post by CoderGoblin »

Glad to be of help.
For future reference str_replace is quicker but preg_replace is more powerful.
Post Reply