We’ve all been to those sites before – the ones that dubiously insert advert links on keywords throughout the page. It’s pretty annoying because they often have nothing to do with the reason(s) why you were on that page to begin with. So now here I am, telling you how to do it easily. But I assure you – my intentions are completely pure!
The task: Link glossary terms to some educational material (coming from a database).
1) Pull your list of terms from the database into an array. Call it $glossary_terms
2) Run a preg_replace command on your page content:
$replace='$0';
$updated_content=preg_replace('/b('. implode('|',$glossary_terms). ')b/i',$replace,$content);
3) Display the $updated_content
link instead of the original $content
.
Explanation
preg_replace() takes either strings or arrays as input, which is really helpful in situations like this where you have an array of terms to which content gets checked against.
The b modifier signifies word boundaries (spaces, punctuation, etc).
The i modifier tells to a case-insensitive search.
Thanks go to xblue and MarkR on PHPBuilder.com for the pointers (especially xblue for pretty much just handing me the answer!).