Jump to content

Regexp replaced with array!


silviuchingaru

Recommended Posts

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!
Link to comment
Share on other sites

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]
Link to comment
Share on other sites

[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.
Link to comment
Share on other sites

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]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.