silviuchingaru Posted January 20, 2007 Share Posted January 20, 2007 Hello!I have the folowing Array defined:[code]$text = Array ( [greeting] => Hello[date] => Some Date ) [/code] I also have a page.tpl that has some tags in it like {greeting} and {date}.I also have a function to preg_replace {tags} with array[tagName] but it is not working:[code]preg_replace("/\{(\w+)\}/",$text["\\1"],contentOfpage.tpl);[/code]If I replace $text["\\1"] with a "text" not a var it works perfectly. Where is my mistake. I read docs and tried codes for almost 5 hours and now I'm running out of pattients. PLEAS HELP! Quote Link to comment Share on other sites More sharing options...
c4onastick Posted January 20, 2007 Share Posted January 20, 2007 Preg_replace can run through an array for you. You don't need to specify the sub script. Granted you'll need two arrays to do this, a match array and a corresponding replace array.[code]$patterns = array ( '/\{greetings\}/', '/\{Hello\}/', '/\{date\}/');$replacements = array ( 'salutations', 'Hola', 'Some Date');preg_replace('$patterns', $replacements, $text);[/code] Quote Link to comment Share on other sites More sharing options...
silviuchingaru Posted January 20, 2007 Author Share Posted January 20, 2007 Yes this is the man part. But what if u don't know the order of arrays? Than the code will mess up. Quote Link to comment Share on other sites More sharing options...
c4onastick Posted January 20, 2007 Share Posted January 20, 2007 [quote author=silviuchingaru link=topic=123252.msg509177#msg509177 date=1169312232]Yes this is the man part. But what if u don't know the order of arrays? Than the code will mess up.[/quote]True. You need to have it set up so that the first element in array 1 is replaced by the first element in array 2... etc. Why don't you know the order of the arrays?By the by: '$pattens' shouldn't be quoted above. Oops. Quote Link to comment Share on other sites More sharing options...
silviuchingaru Posted January 20, 2007 Author Share Posted January 20, 2007 Because is a lang file the replace and so the array has so many keys. Anyway I solve it out by adding an /e at the end of regexp. Quote Link to comment Share on other sites More sharing options...
ShogunWarrior Posted January 21, 2007 Share Posted January 21, 2007 You should create a associate array for yourself like so:[code]$assocs = array( '/\{greetings\}/' => 'salutations' ,'/\{Hello\}/' => 'Hola' ,'/\{date\}/' => 'Some Date');[/code]And then automatically get the patterns/replacements:[code]preg_replace(array_values($assocs), array_keys($assocs), $text);[/code] Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.