Forum Moderators: coopster
I need to make each word a link, example;
<a href="http://www.mysite.com/search.php?=this">this</a>
<a href="http://www.mysite.com/search.php?=is">is</a>
<a href="http://www.mysite.com/search.php?=text">text</a>
<a href="http://www.mysite.com/search.php?=from">from</a>
And so on..
I can't seem to think of a way to do this that would be dynamic, so i could use it no matter how many words are returned from the origional query.
Can anyone help?
echo preg_replace("/\w+/", "<a href=\"search.php?var=$0\">$0</a>", $txt); $pattern = "/\w+/e";
$replacement = "'<a href=\"search.php?var=' . htmlentities('$0') . '\">' . htmlentities('$0') . '</a>'";
echo preg_replace($pattern, $replacement, $txt);
The "e" modifier evaluates the replacement string as PHP code and uses the result for replacing the search string.
Another variation of your search pattern would also handle certain characters that you may sometimes expect to see in words such as hyphens, ampersands, or an apostrophe --
<pre>
<?php
$txt = "How about some Candy? We have M&M's, Take5 and sugar-free gum! :-)";
echo "$txt\n";
$pattern = "/\w[-'&\w]*/e";
$replacement = "'<a href=\"search.php?var=' . htmlentities('$0') . '\">' . htmlentities('$0') . '</a>'";
echo preg_replace($pattern, $replacement, $txt);
?>
</pre>
Just some additional thoughts to consider.