Msg#: 3643929 posted 3:37 pm on May 7, 2008 (gmt 0)
Friends and php gurus, This is what I am trying to do.
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.
Msg#: 3643929 posted 7:34 pm on May 7, 2008 (gmt 0)
preg_replace is still what you want.
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.
Msg#: 3643929 posted 7:58 pm on May 7, 2008 (gmt 0)
The eval modifier is a pretty nifty thing to use, however, I feel that unless it's something relatively small (such as what you have here changing the case-so there's no point in changing it) it is cleaner to use preg_replace_callback [php.net] to modify the replacement string. Just for future reference in case you need to manipulate it in a more complicated way than changing the case :)