Web Hosting Talk







View Full Version : Highlight words (PHP)


actionman
12-13-2005, 09:20 AM
hi,

I have a few ideas but i need something a lot better so please help.

I am trying to highlight all the words that match a given string.

for example.

i want something like this,
http://domain.com/highlight.php?url=www.yahoo.com&string=blahblah

then it should search the yahoo.com's page and highlight all the "blahblah" words.

Any idea how should i do that or has it been coded before ?

thanks

error404
12-14-2005, 01:15 AM
A clumsy and naive way of doing it would be:

$new = preg_replace("/\b($word)\b/i", "<span class='highlight'>\1</span>", $string);


This is probably a bad idea on any sort of marked-up text, as it'll clobber parameter names and such as well. You need a state machine to fix that.

actionman
12-14-2005, 02:17 AM
thanks for the reply,

that's what i have in mind but how do you grab words from a given url and "highlight" them ?

Dark Light
12-14-2005, 09:14 AM
Hello,

If you wanted to get the words from the url, such as 'highlight.php?highlight=word', you might try doing:

$word = $_GET[highlight];
Put that before the preg_replace(); that error404 wrote.
You might want to do some checks on that as-well. ;)

I hope that helps :), if that's not you wanted, I apoligise,
- Dark Light.

error404
12-14-2005, 09:19 AM
Note that the \1 in my code should be a double backslash (or $1 instead if you're using a non-archaic PHP version).