Forum Moderators: coopster
a string of text and change the word/s listed there into links if the words are found from the list.
example: text = "foo is foober". list = "foo, foober"
the word "foo" and "foober" should change into a link.
using str_replace it would change "foo" in "foo" and "foo" in "foober" into links.
Anyone can shed light on this? I am currently testing the preg_replace and experiencing some problems.
Thanks.
$string = "foo is foobar, baz is widgets";
$wordlist = array("/(foo(?!bar))/","/(foobar)/","/(widgets)/");
$string = preg_replace($wordlist,"<a href=\"$1.html\">$1</a>");
This will replace each word in the list with a link to a page with the same name. Not that the first word will only match "foo" as long as it's not followed by "bar". This will ensure that foo in foobar isn't linked. It is also possible to use "\b" before and after each word. It will then only match whole words.
$wordlist = array("/(\bfoo\b)/","/(\bfoobar\b)/","/(\bwidgets\b)/");
The parenthesis lets you use the matched word in the replacement string...
<?
$string = 'one two three';$tolinks = array(
'/\b(one)\b/i',
'/\b(three)\b/i',
// ... etc...
);
$string = preg_replace($tolinks, '<a href="$1">$1</a>', $string);
?>
That would leave $string as '<a href="one">one</a> two <a href="three">three</a>'.
If it was a really big list of words to be linkerised, maybe you could also do something like make a simple array of words, then loop through it and add the "/\b...\b/i" bits...
[ edit: added code style tags. didn't seem to do much in the preview? :) ]
[edited by: mischief at 3:23 am (utc) on April 18, 2003]