...

View Full Version : Find/Replace only *one* instance



Pennimus
08-20-2007, 12:16 PM
I have written a script that scans each new entry in my database for keywords and phrases that exist elsewhere on my site, in order that hyperlinks are automatically created to relevant content. It's very straight forward, simply looping through existing database entries looking for matches in the text, and using str_replace to insert the links where a match is found.

I'm at an impasse though because sometimes I end up with many of the same link appearing in each entry - I'd want to limit it to a maximum of one of each link (as well as limiting it to a maximum number of links overall - although that part is easy).

I'd thought of adding each keyword or phrase to an array to check against before inserting a link, but I don't think this will work since str_replace does all replacements at once. I then thought of splitting the text into an array and looping through it replacing one word at a time, but that won't work because many of the keywords are two or more words. So in short, I'm stumped. Any ideas?

(I know the Alinks extension for Wordpress can do this, but I've not had much luck reverse engineering it because it's a rather complicated collection of scripts for me).

NancyJ
08-20-2007, 01:36 PM
If you use preg_replace you can pass a limit parameter to specify the maximum number of matches to replace. I've never actually tried it but it should work for you.
http://www.php.net/manual/en/function.preg-replace.php

Pennimus
08-20-2007, 03:22 PM
Oh nice, thanks Nancy. Nice and simple :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum