Welcome to WebmasterWorld Guest from 22.214.171.124
replace all occurrences of the words in an array to links to their tag pages (urls).
So for eg:
$tags = array("fruits", "vegetables", "fiber");
I would like to replace:
$str = "I like fruits. Vegetables are not my favorite. ";
I like <a href="/tags/fruits">fruits</a>. <a href="/tags/vegetables">Vegetables</a> are not my favorite.
PLEASE note that I would like to ignore the case while comparing/matching and would like to keep the same case in the actual string. Check how Vegetables got changed to a link to vegetable regardless of the case. So my source string does not change (in html display), only the links are added to their tag urls.
I tried using str_ireplace but could not find a way to remmember the original word. Any help will be appreciated.
Pls note that for all matching words (ignoring case), I would like to add a hyperlink but I do not want to change the original word.
So Vegetables would become <a href="/tags/vegetables">Vegetables</a>
vegetables would become <a href="/tags/vegetables">vegetables</a>
vegeTables would become <a href="/tags/vegetables">vegeTables</a>
pls note that the link url is /tags/vegetables . What I am doing is if I find tags in an article, I am linking to the tag page.
Hope I made my requirement clear.
using the /i switch in the pattern for preg_replace() will match case-insensitively, so the pattern "/vegetables/i" will match Vegetables, vegETables, VEGETABLES, or VeGeTaBlEs.
If you take it a step further and use the /e switch, you can evalute the replace in a similar fashion to using the eval [us.php.net] function, which will allow you to use strtolower() in your replacement to ensure that the link is lower case.
preg_replace("/vegetables/ei","\"<a href='/tags/\".strtolower(\"\\0\").\"'>\\0</a>\"", $your_string);