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
https://forums.phpfreaks.com/topic/34983-regexp-replaced-with-array/
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]
[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.
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]

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.