Page 1 of 1

[solved]help with automated highlighting

Posted: Wed Sep 06, 2006 7:53 am
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.

Posted: Wed Sep 06, 2006 8:06 am
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.

Posted: Wed Sep 06, 2006 8:38 am
by Black_cage85
I used 'str_replace' and that did the trick, thanks for your help.

Posted: Wed Sep 06, 2006 8:45 am
by CoderGoblin
Glad to be of help.
For future reference str_replace is quicker but preg_replace is more powerful.