str_replace only once
We use a content admin system to post articles to a DB.
Upon submission, I want the script to search for the first instance of a proper name - check it against a set of data, and if there's a match, add an appropriate link.
1) This is partly simple if using a set of data around 100 names or so. Loop through each name in the list ... and if there's a match in the text, add the corresponding link:
The trouble is, I only want it to do this on the first instance. I am (I think) quite familiar with the ever-growing and wonderful list of PHP string functions ... and I know about functions that will *find* the first instance. But I don't know how to only act upon that first instance.
foreach ($team_name as $key=>$value)
Can someone suggest the combination of functions I'm looking for. For example, if the team name "Bears" appears 3 times in an article, I only want to do the "str_replace" on the first instance.
Alternatively, can it be done with "ereg_replace"
2) Can someone suggest an alternative method of checking for matches. Let's say I want to check against a list of names that reside in a DB. Instead of just 100 team names, I want to check against 5,000 player names. I don't think I want to loop through every name looking for a match (as I'm doing above). I *could* do that -- but I would think there's a better way. I don't know.
You could use a preg_replace call for it. Something like this (untested):
$content = preg_replace("/^(.*)?$value/","//1<a href='/m/?team=$key'>$value</a>",$content);
Another thing you might want to do is make the writer hardcode some sort of markup tag in there, like [author]John Smith[/author] and do a str_replace("[author]$value[/author]",...);
Having just looked at "preg_replace" - I noticed that it has a 4th parameter ... the "limit" parameter.
Gee - isn't that nice :-)
If only str_replace had that, I could avoid all this trouble.
Nevertheless ... I can still use "preg_replace" without having to use the complicated regular expression hieroglyphics, and just use limit=1. Of course, preg_replace is also slower than str_replace.
I think it's time to write the PHP people and ask them to put a limit parameter into str_replace :-)