Anyway I have a query. What I am trying achieve is to do some on the fly linking. What I have is some content from a DB, and within the content if a particular word appears then I would like to insert a link to the product page.
Now I'm not quite sure the best way of implementing this. whether I should create a keywords table in the DB and then compare the content with the keywords table?
Msg#: 8371 posted 12:42 am on May 27, 2005 (gmt 0)
Why not just modify the content in the database to include the link?
Because then it's harder to change them on the fly.
I presume it's a small set of links and words (like a few hundred at most)? Since you're going to need to get all the words into an array for every page, I would probably just store it in a CSV file, upload the words and the replacement link to an array, and then use preg_replace or str_replace, sending it the array of word, the array of replacement links and the text from the DB.
str_replace has the advantage of speed, but the disadvantage of not being able to distinguish whole words from strings within words.
Actually, whole/partial words can be easily distinguished. Simply add a space to the start and end of the search string and then make sure to add them back into the replacement string. On a query such as mentioned, those microseconds are going to count.
I understand your point. Especially if there's a need to count the total number of words or perhaps reuse the words themselves, for example in the event of an case-insensitive search where we want the case to be restored. However, if the search isn't that specific, it is just as easy I mentioned. Using str(i)_replace on an array of keywords will replace every instance of the word with the replacement string. The only areas where this might be a problem is if the search term is at the first or last of the sentence (case or followed by puncuation).
I wasn't trying to say that this situation doesn't call for regular expressions, just that it's always best to evaluate the need before using them. :)