views:

54

answers:

2

I have a database table full of words. What I would like to do is to have a way to show the user in the html in the form of a hyperlink, any of these keywords. Kind of like you see on many forums now a days. When a keyword is noted in the html, it becomes clickable. Is there a way to do this? I'm using php.

Thanks

A: 

You create a table of link URLs with an ID field and a field that stores the ID of a row in your keyword table. You select the linked url with something like:

select keywords.name, links.url
from keywords, links
where keywords.id = links.keywords_id
and keyword.name = 'keyword_in_the_html'
Jeff Ober
Thanks Jeff. I have just about this much down so far but I'm kind of stuck on how to parse the html. I mean, each word would have to be evaluated and compared against the links table. I just don't know how to do this. Do you have any suggestions how to parse the html?
ned
You could use a simple regular expression to break it up by word boundaries, e.g. preg_match('/\b(.+?)\b/', $html).
Jeff Ober
A: 

The most obvious way I can think of doing this is looping through every keyword from your database, and running a preg_replace on your HTML for each (just replace each word with an appropriate hyperlink).

Your regular expression is likely to be complex, because you will need to make sure that none of the word replacements interfere with your HTML, and you will also want to make sure you only replace whole words and not partial words.

Lastly, if your word database is very large, this will be expensive to do on every request. So consider performing it once and storing the result.

Alternatively, offload the processing to the client and do the replacement with JavaScript. Modifying HTML tags may not be a problem then, because you should be able to run the replace on only the text nodes of the DOM. But again, if your database is large, you will have to send a long list of words to the client for the JavaScript to loop through.

Ben James
Thanks Ben. The table exceeds 12 thousand rows so I'm thinking it will be quite costly indeed. Say I was going to use preg_replace; how would I parse all the words in the document? I'd need to somehow get them into an array, no? I mean, somehow the words would all have to be broken down to compare against the database.
ned